1
我試圖將子視圖動態地充滿父視圖,但會引發錯誤。將RelativeLayout子項添加到父佈局中動態地不起作用
我嘗試添加下面彼此
這裏每個RelativeLayout的孩子是我的代碼:
父佈局
<RelativeLayout
android:id="@+id/work_list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</RelativeLayout>
子佈局
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff">
<ImageView
android:id="@+id/work_pic"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:src="@mipmap/image_placeholder"/>
</RelativeLayout>
通貨膨脹代碼:
RelativeLayout parent = (RelativeLayout) findViewById(R.id.work_list);
//array containing all children ids
ArrayList<Integer> children = new ArrayList<>();
//adding 10 children to the parent
for(int i=0;i<10;i++) {
RelativeLayout child = (RelativeLayout) findViewById(R.id.work_list); //new child
child.setId(i); //setting an id for the child
children.add(i); //adding the child's id to the list
if(i!=0) //if it isn't the 1st child, stack them below one another, since the 1st child does not have a child to stack below
{
RelativeLayout.LayoutParams params
= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, children.get(i - 1)); //stack it below the previous child
child.setLayoutParams(params);
}
parent.addView(child); //add the new child
}
的錯誤,我得到:
致:java.lang.IllegalStateException:指定的子 已經有母。您必須先調用孩子父母 上的removeView()。在 com.hellotest.TestingDynamics.onCreate(TestingDynamics.java:43)
線43分,這條線:
parent.addView(child);
我在做什麼錯?如果我錯了,我的代碼有什麼更正,夥計們?
這擺脫了錯誤,但我沒有看到兒童佈局視圖現在。看起來他們不會充氣:/ – Dinuka
哦,當然沒有出現,我沒有設置佈局被誇大:D我該怎麼做配偶? – Dinuka
@Earthling你已經接受了答案 - 你還需要幫助嗎?通脹是用構造函數創建佈局的替代方法,因此如果以編程方式創建佈局,則不需要對佈局進行膨脹。我會說你沒有(沒有)看到他們,因爲他們是空的,他們的大小設置爲'WRAP_CONTENT' – wasyl