示例代码:
前端代码:
<?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;
}
}
}