简体   繁体   中英

Multiple button using same xml layout file

i want to create multiple button from same xml resource for this i am creating am xml layout in which i define button in aa xml file

<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>

and then in code i create multiple button using button which i define in xml the code is like this

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);
        }

Now the problem is that when i create a single it's just work fine but when i create more than 1 button it gives me exception that

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

So, please me in this.

The error is normal, as it says, each view can only be added once.

Move your button XML into a separate file, and inflate it and add it to your LinearLayout inside your for loop.

We can't guess what is your "inputbar" object so we don't know where are you adding the views.

What you can do is this, assuming that your container has the id=@+id/container and is a 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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM