用RadioGroup设置选择题

本文介绍了如何在Android中利用RadioGroup组件创建选择题,并展示了如何在Java代码中监听选中项变化,更新显示结果。示例代码包括布局XML文件和Activity的实现,通过设置OnCheckedChangeListener来判断用户的选择并给出相应反馈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先在布局中设置你想要的布局效果

以我自己为例:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
<TextView 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="少小离家老大回 乡音无改鬓毛衰的作者"
    />
<RadioGroup
    android:contentDescription="作者"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/radioGroup"
    >
    <RadioButton 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="李白"/>
    <RadioButton 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="李清照"/>
    <RadioButton 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="贺知章"/>
    <RadioButton 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="杜甫"/>
</RadioGroup>
<TextView 
    android:id="@+id/tvSex"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="作者是:"
    />
</LinearLayout>

然后在Java代码中写自己的程序



public class RadiioGroupActiviy extends Activity {
TextView tv = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.radiogroup_main);
//根据ID找到该文本控件
       tv = (TextView)this.findViewById(R.id.tvSex);
     //根据ID找到RadioGroup实例
         RadioGroup group = (RadioGroup)this.findViewById(R.id.radioGroup);
      //绑定一个匿名监听器
       group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
           
            @Override
           public void onCheckedChanged(RadioGroup arg0, int postion) {
                // TODO Auto-generated method stub
               //获取变更后的选中项的ID
                int radioButtonId = arg0.getCheckedRadioButtonId();
                //根据ID获取RadioButton的实例
               RadioButton rb = (RadioButton)findViewById(radioButtonId);
                 //更新文本内容,以符合选中项
         
              if (rb.getText().equals("贺知章")){
  Toast.makeText(RadiioGroupActiviy.this, "选择正确",0 ).show();
  }
                else{
                  Toast.makeText(RadiioGroupActiviy.this, "错误", 0).show();
                  }
 

                tv.setText("您的选择是:" + rb.getText());
                
           }
            
        });
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值