Android中的的RadioGroup与RadioButton向来是组合使用的,它用于创建一组按钮之间相互排斥的按钮组(即:RadioGroup),在同一个RadioGroup中,只能有一个RadioButton处于处于选中状态或者同时都不选,
效果图如下:
1.0 activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center"
tools:context="com.lgl.radiobutton.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sex" />
<RadioGroup
android:id="@+id/radio_group_sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/man"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/man" />
<RadioButton
android:id="@+id/woman"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/woman" />
</RadioGroup>
</LinearLayout>
2.0 MainActivity:
package com.lgl.radiobutton;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class MainActivity extends Activity {
private RadioGroup rg_sex;
private RadioButton man;
private RadioButton woman;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取控件
rg_sex = (RadioGroup) findViewById(R.id.radio_group_sex);
man = (RadioButton) findViewById(R.id.man);
woman = (RadioButton) findViewById(R.id.woman);
/**
* 1.0 通过onCheckedChanged方法中的int参数获取RadioButton的Id
*/
rg_sex.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
if (arg1 == R.id.man) {
Toast.makeText(MainActivity.this,
"您选择的性别是:" + man.getText().toString(),
Toast.LENGTH_SHORT).show();
}
if (arg1 == R.id.woman) {
Toast.makeText(MainActivity.this,
"您选择的性别是:" + woman.getText().toString(),
Toast.LENGTH_SHORT).show();
}
}
});
/**
* 2.0 通过RadioGroup的getCheckedRadioButtonId方法获取RadioButton的Id
*/
/*rg_sex.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
int id = arg0.getCheckedRadioButtonId();
if (id == R.id.man) {
Toast.makeText(MainActivity.this,
"您选择的性别是:" + man.getText().toString(),
Toast.LENGTH_SHORT).show();
}
if (id == R.id.woman) {
Toast.makeText(MainActivity.this,
"您选择的性别是:" + woman.getText().toString(),
Toast.LENGTH_SHORT).show();
}
}
});*/
}
}
总结: 由于RadioButton的id是通过setOnCheckedChangeListener方法获取的,所以当设置了某个RadioButton为默认值时,不通过点击事件是获取不到RadioButton的id的。