0

这段代码有什么问题?它给了我这个错误:

指定的孩子已经有一个父母。您必须首先在孩子的父母上调用 removeView()。

    final LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    final LinearLayout ll2 = new LinearLayout(this);
    ll2.setOrientation(LinearLayout.HORIZONTAL);

        for(int i = 0; i < 20; i++) {
             CheckBox cb = new CheckBox(getApplicationContext());
             TextView txt = new TextView(getApplicationContext());
                txt.setText("test!");
                ll2.addView(cb);
                ll2.addView(txt);
                ll.addView(ll2); //ERROR HERE
            }
        sc.addView(ll);
4

1 回答 1

2

由于它在循环中,因此您ll.addView(ll2)多次调用。将其移到 for 循环之外:

final LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

final LinearLayout ll2 = new LinearLayout(this);
ll2.setOrientation(LinearLayout.HORIZONTAL);

for(int i = 0; i < 20; i++) {
    CheckBox cb = new CheckBox(getApplicationContext());
    TextView txt = new TextView(getApplicationContext());
    txt.setText("test!");
    ll2.addView(cb);
    ll2.addView(txt);
}

ll.addView(ll2);
sc.addView(ll);
于 2013-03-13T00:10:31.990 回答