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

前端 未结 3 1595
予麋鹿
予麋鹿 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

    You're using a for-loop to add the same references to TextViews to your TableRow. So in the next iteration of the loop, the same objects are added to the TableRow (or TableLayout), again! They already have a parent by then.

    Try to initialize the TableRow and TextView objects inside the (outer)for-loop.

    EDIT: Modified your code.

    void setCalendario(List> l) {
        // Here we initialize the objects we re-initialize every iteration of the loop
        TableLayout table = (TableLayout)findViewById(R.id.list_tableLayout1);
        for (ArrayList al : l) {
            TableRow tr = new TableRow(this);
        // I can't believe a freshly initialized TableRow object has views attached...
            tr.removeAllViews();
            tr.setPadding(0,10,0,10);
        // Not sure why these layout params are needed already, as they are specified
        // when adding this TableRow to the TableLayout object as well.
            tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            TextView tv_item1 = new TextView(this);
            TextView tv_item2 = new TextView(this);
            TextView tv_item3 = new TextView(this);
            int i = 0;
            for(String s : al) {
                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));
                }
            }
        }
        } 
    

提交回复
热议问题