我在代码中动态绘制table。我从布局中得到的tablerow只是在XML中进行硬编码。我不知道为什么会收到这个错误,并且完全没有想法。

 TableRow tr = (TableRow) findViewById(R.id.tr);
        TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);

    TextView textView1 = new TextView(this);
    textView1.setGravity(Gravity.CENTER);
    textView1.setBackgroundResource(R.drawable.cell_shape);
    textView1.setText("1");
    textView1.setLayoutParams(rowParams);
    tr.addView(textView1);

    TextView textView2 = new TextView(this);
    textView2.setGravity(Gravity.CENTER);
    textView2.setBackgroundResource(R.drawable.cell_shape);
    textView2.setText("2");
    textView2.setLayoutParams(rowParams);
    tr.addView(textView2);

    TextView textView3 = new TextView(this);
    textView3.setGravity(Gravity.CENTER);
    textView3.setBackgroundResource(R.drawable.cell_shape);
    textView3.setText("3");
    textView3.setLayoutParams(rowParams);
    tr.addView(textView3);

    TextView textView4 = new TextView(this);
    textView4.setGravity(Gravity.CENTER);
    textView4.setBackgroundResource(R.drawable.cell_shape);
    textView4.setText("4");
    textView4.setLayoutParams(rowParams);
    tr.addView(textView4);

    TextView textView5 = new TextView(this);
    textView5.setGravity(Gravity.CENTER);
    textView5.setBackgroundResource(R.drawable.cell_shape);
    textView5.setText("5");
    textView5.setLayoutParams(rowParams);
    tr.addView(textView5);

    TextView textView6 = new TextView(this);
    textView6.setGravity(Gravity.CENTER);
    textView6.setBackgroundResource(R.drawable.cell_shape);
    textView6.setText("6");
    textView6.setLayoutParams(rowParams);
    tr.addView(textView6);

    TextView textView7 = (TextView) findViewById(R.id.tv);
    TableRow.LayoutParams params = (TableRow.LayoutParams)textView7.getLayoutParams();
    params.span = 6;
    textView7.setLayoutParams(params);

    //tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

    //next row
    TableRow trNew = (TableRow) findViewById(R.id.newline);
    TableRow.LayoutParams rowParams1 = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);

    TextView textView8 = (TextView) findViewById(R.id.model);
    textView8.setGravity(Gravity.CENTER);
    textView8.setBackgroundResource(R.drawable.cell_shape);
    textView8.setText("Check");
    trNew.addView(textView8);


该错误是由以下原因引起的:trNew.addView(textView8);

我的错误消息是:

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

最佳答案

如果要使用在trNew.addView(textView8);中创建的TextView,请删除XML。如果要使用动态创建的TextView,请替换

TextView textView8 = (TextView) findViewById(R.id.model);


通过

 TextView textView8 = new TextView(this);

10-07 18:38