1、设置监听器时implements onCheckChangeListener
导入包选择 android.widget.radioGroup下的接口!!
2、哪个按钮被选中?在方法中设置参数checkId
public void onCheckChanged(RadioGroup, int checkId){
switch(checkId){
case R.id.radio0:
Log.i(“tag”,”当前点击了男的”);//输出日志
break;
1. 实现OnCheckedChangeListener的独立接口方法,必须要import
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
注意:
对于其他的Button(包括ToggleButton)、CheckBox等控件,导入的包为:
import android.widget.CompoundButton.OnCheckedChangeListener;
然后重载OnCheckedChangeListener的时候是这样的:
public void onCheckedChanged(CompoundButton arg0, boolean arg1),即第一个参数是CompoundButton类型
2. RadioButton要进行OnCheckedChangeListener()方法重载:
public void onCheckedChanged(RadioGroup group, int checkedId)
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.radiogroup.MainActivity" >
<RadioGroup
android:orientation="horizontal"
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="男" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女" />
</RadioGroup>
</RelativeLayout>
package com.example.radiogroup;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class MainActivity extends Activity implements OnCheckedChangeListener {
private RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rg = (RadioGroup) findViewById(R.id.radioGroup1);
// 通过接口实现监听
rg.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radio0:
Log.i("tag", "男");
break;
case R.id.radio1:
Log.i("tag", "女");
break;
}
}
}