RadioButton 是一个单选控件,在一个RadioGroup中,各个RadioButton是互斥的
XML文件:
<RelativeLayout 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"
tools:context="${relativePackage}.${activityClass}" >
<RadioGroup
android:id="@+id/RadioGroup1"
android:layout_width="fill_parent"
android:layout_height="match_parent"
>
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="42dp"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/radioButton1"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/radioButton2"
android:text="RadioButton" />
</RadioGroup>
</RelativeLayout>
使用OnCheckedChangeListener监听:
package com.example.textview;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class MainActivity extends Activity {
private RadioGroup RadioGroup1=null;
private RadioButton RadioButton1=null;
private RadioButton RadioButton2=null;
private RadioButton RadioButton3=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup1=(RadioGroup)findViewById(R.id.RadioGroup1);
RadioButton1=(RadioButton)findViewById(R.id.radioButton1);
RadioButton2=(RadioButton)findViewById(R.id.radioButton2);
RadioButton3=(RadioButton)findViewById(R.id.radioButton3);
RadioGroup1.setOnCheckedChangeListener(listener);
}
private OnCheckedChangeListener listener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId==RadioButton1.getId())
{
System.out.println("button 1");
}
else if(checkedId==RadioButton2.getId())
{
System.out.println("button 2");
}
else if(checkedId==RadioButton3.getId())
{
System.out.println("button 3");
}
}
};
}