2011-12-31 90 views
0

我有一个应用程序,它可以动态地从json数据添加单选按钮。我真的不知道如何找出哪些被选中。有radioButton.isSelected()radioGroup.getCheckedRadioButtonId(),但由于它是动态创建的,我不能使用所有对象的名称。如何循环遍历所有动态创建的单选按钮,以及如何识别它们?

有没有办法在创建时将它们添加到组中,然后在所有组件中循环遍历它们?我有多个radiogroups,并不是所有的,但大多数都应该被检查。

我使用api lvl 7(2.1),我对此很新。请详细解释。

回答

1

您可以使用ArrayList。

ArrayList<RadioButton> radioButtons = new ArrayList<RadioButton>(); 
//create your new button and add it here. 
radioButtons.add(radioButton); 

然后遍历列表,如果你需要检索每个按钮,使用for循环:

for (int i=0;i<radioButtons.size();i++){ 
    RadioButton button = radioButtons.get(i); 
    //do what you need with the button 
} 

如果你需要每个单选按钮有一定的数据,那么你可以做:

radioButton.setTag("tag"); 

,然后当你通过迭代循环,你可以做button.getTag();

或者如果你只是想得到所选的一个:

RadioButton button = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId()); 

我想我涵盖了一切从你的问题,也许更多。如果我错过了任何内容或需要提供任何其他解释,请告知我们。

+0

这与http://www.devx.com/tips/Tip/13741(如何使全局变量)一起解决了它。非常感谢! – 2011-12-31 12:08:53

相关问题