Android: You must call removeView() on the child's parent first 2

前端 未结 3 1594
予麋鹿
予麋鹿 2021-01-25 06:00

I have a problem in Android creating a table adding rows dynamically. The error message is:

The specified child already has a parent. You mu

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-25 06:32

    because you are trying to put the same textView many times. you can use it only once, so you have to instantiate it again and again :

    // you remove the definition of the text views here and you put it inside the loop
        for (ArrayList al : l){
            int i = 0;
            for(String s : al){
     TextView tv_item2 = new TextView(this);
    TextView tv_item1 = new TextView(this);
    TextView tv_item3 = new TextView(this);
                if (i == 0){
                    i++;
    
                    tv_item1.setText(s);
                    tv_item1.setGravity(Gravity.CENTER);
                }
                if (i == 1){
    
                    tv_item2.setText(s);
                    tv_item2.setGravity(Gravity.CENTER);
                    i++;
                }
                if (i == 2){
    
                    tv_item3.setText(s);
                    tv_item3.setGravity(Gravity.CENTER);
                    tr.addView(tv_item1);
                    tr.addView(tv_item2);
                    tr.addView(tv_item3);
                    table.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                }
            }
        }
    

    This is not the best way to do it, you should may be creat a methode that takes your "i" as parameter and returns a TextView (with gravity center ... and your staff).

提交回复
热议问题