[英]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.