【Android之单选按钮】RadioButton

【Android之单选按钮】RadioButton

单选按钮必须包含在RadioGroup中,相当于放在盒子里,为RadioGroup设置id为:nan_rsp;两个按钮设置id为:nan_rg_boy、nan_rg_girl。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="【单选按钮RadioButton的使用】:"
       android:textSize="26sp"
        android:textColor="#EF3C00"
        android:textStyle="italic"
        android:layout_marginBottom="20dp"/>
<RadioGroup
    android:id="@+id/nan_rgp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <RadioButton
        android:id="@+id/nan_rg_boy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="男"
        android:textSize="24sp"/>
    <RadioButton
        android:id="@+id/nan_rg_girl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="女"
        android:textSize="24sp"/>
</RadioGroup>
    <TextView
        android:id="@+id/nan_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"/>
</LinearLayout>

Activity中的代码如下:

public class MainActivity extends AppCompatActivity  {
private RadioGroup radioGroup;//声明单选按钮变量
private TextView textView;//声明显示的变量
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //将声明的变量绑定按钮的id
        radioGroup=findViewById(R.id.nan_rgp);
        textView=findViewById(R.id.nan_show);
        //利用setOnCheckedChangeListener()为radioGroup建立监听
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //判断点击的是哪个radioGroup
                if(checkedId==R.id.nan_rg_boy){
                    textView.setText("你选择的性别是:男");
                }else{
                    textView.setText("你选择的性别是:女");
                }
            }
        });

    }
}

结果图:

初始化图:

选择后:

 

结论:单选需要放在一个盒子里(RadioGroup)里,然后再Activity中为“盒子”建立监听(setOnCheckendChangeListenter())。

 

【今日每句】:手懒的,要受贫穷;手勤的,却要富足。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值