繁体   English   中英

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

[英]Multiple button using same xml layout 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>

然后在代码中,我使用在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.

所以,请我在这。

如上面所说,该错误是正常现象,每个视图只能添加一次。

将按钮XML移到一个单独的文件中,并对其进行充气,然后将其添加到for循环内的LinearLayout中。

我们无法猜测您的“ 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);
        }

暂无
暂无

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

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