【发布时间】:2013-12-08 17:12:28
【问题描述】:
我正在尝试在下图中准备自定义 radiogroup 布局。我有将近 8-10 行来做这件事。因此,我准备了一个水平方向的linear layout,并以编程方式添加了imageview、textview 和radiobutton。
所以如果我选中一个radio button,其他单选按钮应该会自动取消选中。在执行该任务之前,我遇到了另一个问题,如果我的单选按钮被选中一次,那么即使单击了单选按钮,单选按钮也不是不可选中的。下面是我的代码。
public class MainActivity extends Activity{
RadioButton[] radioBtns = new RadioButton[10];
String texts[] = {"text1", "text2", .... "text10"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
entireLayout = (LinearLayout)findViewById(R.id.main_layout);
for(int i =0; i<10; i++)
{
LinearLayout rowLayout=new LinearLayout(this);
radioBtns[i] = new RadioButton(this);
radioBtns[i].setId(i);
radioBtns[i].setOnCheckedChangeListener(cblistener);
ImageView imageView = new ImageView(this);
TextView tv = new TextView(this);
tv.setText(texts[i]);
rowLayout.addView(imageView);
rowLayout.addView(tv);
rowLayout.addView(radioBtns[i]);
entireLayout.addView(rowLayout);
View line = new View(this);
line.setBackgroundColor(getResources().getColor(R.color.horizontallinecolor));
entireLayout.addView(line, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 1));
}
}
CompoundButton.OnCheckedChangeListener cblistener = new CompoundButton.OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton checkedbutton, boolean paramAnonymousBoolean)
{
switch (checkedbutton.getId())
{
case 0:
Log.d("tag", "checked 0th position");
break;
..........................
..........................
}
}
};
}
我通过记录日志观察到。控件在被选中时第一次进入 onCheckedChanged() ,但在未选中时则不会。我想知道这些是如何无法检查的。
或根据我的要求,我还有一个想法来准备这个布局,就像我为 xml 中的行准备一个布局一样。然后将视图膨胀 10 次。但是,我怎样才能只检查一个单选按钮,以便取消选中其他选定的单选按钮。有人可以建议我如何通过最好的方式实现这种radiogroup吗?
注意:我保留上面的代码是为了展示我尝试过的内容。如果这是完全错误的方式,请放轻松,请建议我如何完成。
【问题讨论】:
-
请把版面贴出来好吗?因此,要更轻松地了解您想要做什么。
-
@Klaus66 感谢您的评论。除了线性布局外,我在主布局中什么都没有。我所做的只是动态添加视图,这已经在我的上面的代码中了。我正在尝试实现图像中显示的内容。
标签: android radio-button radio-group