简体   繁体   English

使用相同xml布局文件的多个按钮

[英]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 我想为此从同一个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>

and then in code i create multiple button using button which i define in xml the code is like this 然后在代码中,我使用在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);
        }

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. 将按钮XML移到一个单独的文件中,并对其进行充气,然后将其添加到for循环内的LinearLayout中。

We can't guess what is your "inputbar" object so we don't know where are you adding the views. 我们无法猜测您的“ inputbar”对象是什么,因此我们不知道您将视图添加到何处。

What you can do is this, assuming that your container has the id=@+id/container and is a LinearLayout: 您可以执行以下操作,假设您的容器具有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);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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