2

このために同じ xml リソースから複数のボタンを作成したい xml ファイルでボタンを定義する xml レイアウトを作成しています

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <Button
            android:id="@+id/inputbox"
            style="@style/textstyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/inputbox"
            android:text="B" />

</LinearLayout>

次に、コードで、xmlで定義したボタンを使用して複数のボタンを作成します。コードは次のようになります

View view = inputboxview.findViewById(R.id.inputbox);
        ((ViewGroup) view.getParent()).removeView(view);

        //Add input boxes in control view
        for(int i=0; i<guess_world.length(); i++)
        {
            Button inputbox = new Button(context);
            //Drawable image = context.getResources().getDrawable(R.drawable.inputbox); 
            //inputbox.setBackgroundDrawable(image);
            //inputbox.set
            inputbox = (Button) view;
            inputbar.addView(inputbox);
        }

問題は、単一のボタンを作成すると正常に動作することですが、複数のボタンを作成すると例外が発生することです

java.lang.RuntimeException: 
 java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

では、これでお願いします。

4

2 に答える 2

0

「inputbar」オブジェクトが何であるかを推測できないため、ビューをどこに追加しているのかわかりません。

できることは、コンテナーに id=@+id/container があり、LinearLayout であると仮定すると、次のようになります。

LinearLayout container = (LinearLayout) findViewById(R.id.container);

for(int i=0; i<guess_world.length(); i++)
        {
            Button inputbox = new Button(context); //or inflate from xml
            inputbox.setId(i);
            // TODO: set width and height using LayoutParameters
            container.addView(inputbox);
        }
于 2013-10-02T13:16:06.793 に答える