Android:选择微调项目后动态添加按钮

时间:2012-05-07 03:44:20

标签: java android button spinner

有一段艰难的时间让这个工作,这是我最终的理解作品......

如果我有一个包含文本“[item]是[color]”的微调项目,并且选择此项后,我希望它填充... tablerow或类似的东西(或只是一个relativelayout)。 ..有按钮,会有两个按钮,[item]和[color],一个堆叠在一起。

public void onItemSelected(AdapterView<?> parentview, View arg1, int position, long id) 
{

    final TableLayout t1 = (TableLayout)findViewById(R.id.button_items);
    final TableRow tr = new TableRow(t1.getContext());
ArrayList<String> words = Create_ArrayList(R.raw.titles);  

// Create_ArrayList只解析已知的单词,如[item]和[color]项,并将它们放入一个数组中...以便稍后进行枚举。

String sentence = (String) spin.getSelectedItem();

    if(sentence.contains("[item]"))
    {
        String line = words.get(1);
        ArrayList<String> x = getParts(line);  

// arraylist此时应该只是[item]和[color] ......

        Toast.makeText(getBaseContext(), Integer.toString(x.size()), Toast.LENGTH_SHORT).show();
    for(int i = 0; i<x.size(); i++)
    {
              Toast.makeText(getBaseContext(), x.get(i), Toast.LENGTH_LONG).show();

            Button btn = new Button(tr.getContext());
       btn.setText(x.get(i));
       btn.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
       tr.addView(btn);
       t1.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    }   
}
}

但我一直在......

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

并且按钮不会显示...应用程序只是崩溃...进入一座山。

非常感谢帮助......谢谢大家!

2 个答案:

答案 0 :(得分:1)

这是因为您反复向同一个表行添加相同的按钮。你可以使用一组按钮,

btns = new Button[]{button1, button2, etc...} 

然后说:

for(int i = 0; i < x.size() ; i++ ){
     btn[i] = new Button(tr.getContext());
     btn[i].setText(x.get(i));
     tr.addView(btn[i]);
}

答案 1 :(得分:1)

在第一个代码块中

final TableLayout t1 = (TableLayout)findViewById(R.id.button_items);

您已经拥有了t1的视图,但在第三个代码块中又添加了视图

tr.addView(btn);
       t1.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

这是您例外的原因。

当View已经全部使用时(例如,你使用了findViewById,请不要在其上使用addView)。如果要添加视图,请使用带有新视图的addView。您可以将一些新视图添加到一个视图中,但不能多次添加该视图。

这是我在其他一些帖子中找到的

相关问题