安卓单选按钮

6

我在Android中有一个单选按钮组,看起来像这样:

选择颜色:

  • 红色
  • 蓝色
  • 橙色
  • 绿色

我需要获取所选单选按钮及其值。

我有4个单选按钮,它们都在radiogroup rg中。

rb1a=(RadioButton)findViewById(R.id.rb1a);
rb1b=(RadioButton)findViewById(R.id.rb1b);
rb1c=(RadioButton)findViewById(R.id.rb1c);
rb1d=(RadioButton)findViewById(R.id.rb1d);
tv1=(TextView)findViewById(R.id.tv1);
next1=(Button)findViewById(R.id.next1);
rg=(RadioGroup)findViewById(R.id.rg);

// I have error after this line.please help
rg.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    public void onCheckedChanged(RadioGroup group, int checkedId)
    {

    }

    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
        // TODO Auto-generated method stub

    }
});

你的单选按钮或用户界面是如何定义的? - Pentium10
Sanjeev,别忘了选择一个答案,这样我们就可以关闭这个问题了。 - Gabriel Fair
2个回答

5

您可以使用isChecked()函数测试单选按钮。

例如:

if(radio1_red.isChecked())
{
       txtView.setText("Red button is checked");
}

请看这个示例
你还可以参考android-sdk页面中提供的表单内容获取选中的单选按钮及其值的方法如下:
 private OnClickListener radio_listener = new OnClickListener() {
    public void onClick(View v) {
        // Perform action on clicks
        RadioButton rb = (RadioButton) v;
        Toast.makeText(HelloFormStuff.this, rb.getText(), Toast.LENGTH_SHORT).show();
    }
};

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接