簡體   English   中英

將子視圖添加到相對布局

[英]Adding child views to Relative Layout

盡管我遇到了許多有關相對布局和以編程方式添加子視圖的問題,但我無法解決此問題

for (int i=0; i<views; i++) {

    ImageView img = new ImageView(this);
    LayoutParams img_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    img_params.addRule(RelativeLayout.ALIGN_PARENT_LEFT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    relativeLayout.addView(img, img_params);

    TextView textview = new TextView(this);
    LayoutParams text_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    text_params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    relativeLayout.addView(textview, text_params);
}

我在下面添加了日志:

06-27 11:16:38.849: E/AndroidRuntime(20595): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

您要一遍又一遍地添加相同的View對象。 第一次運行循環時,將添加兩個視圖,並且它們現在有一個父視圖。 它們不能再次添加。

您需要在每次迭代中實例化這些視圖的新實例,以使其工作。

在循環內創建ImageViewTextView新實例

for (int i = 0; i < views; i++) {
    LayoutParams img_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    img_params.addRule(RelativeLayout.ALIGN_PARENT_LEFT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    ImageView img = new ImageView(this);
    relativeLayout.addView(img, img_params);

    LayoutParams text_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    text_params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    TextView textview = new TextView(this);
    relativeLayout.addView(textview, text_params);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM