android 之RadioButton单选控件



示例代码:

前端代码:

<?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"
  >
    <RadioGroup
        android:id="@+id/radioButton_gender"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <RadioButton
            android:layout_gravity="center_horizontal"
            android:text="女"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/radioButton_female"
            />
        <RadioButton
            android:layout_gravity="center_horizontal"
            android:text="男"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/radioButton_male"
            />
    </RadioGroup>
</LinearLayout>

业务逻辑:

package com.example.tf.radiobutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
    //1.寻找控件
    private RadioGroup radioGroup_gender;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    //2.寻找控件
    this.radioGroup_gender = (RadioGroup) this.findViewById(R.id.radioButton_gender);
    //注册一个监听事件
    this.radioGroup_gender.setOnCheckedChangeListener(this);
    }
    /**
     * 当单选按钮的状态发生变化时自动调用的方法
     * @param radioGroup 单选按钮所在的按钮组的对象
     * @param checkedId  用户选中的单选按钮的id值
     */
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        //得到用户选中的  RadioButton对象
         RadioButton radioButton_checked = (RadioButton) radioGroup.findViewById(checkedId);
        //将得到的内容转化成字符串形式
         String gender = radioButton_checked.getText().toString();

         Toast.makeText(this, gender, Toast.LENGTH_SHORT).show();

        switch (checkedId){
            case R.id.radioButton_male:
                //当用户点击男性按钮时执行的代码
                System.out.println("男性");
                break;
            case R.id.radioButton_female:
                //当用户点击女性按钮时执行的代码
                System.out.println("女性");
                break;
        }
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值