radioGroup可以实现单选
注意 OnCheckedChangeListener() 为radioGroup的方法,需要import android.widget.RadioGroup.OnCheckedChangeListener;
而onCheckedChanged() 方法的checkedId参数为被选中radioButton的ID,可以在switch的case中用R.id.radio0的形式去匹配。
当然,也可以单个的RadioButton来实现监听,而不是用RadioGroup判断ID 的形式。
package com.example.test_radio_group;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RadioButton;
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 boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb;
String mtext;
rb = (RadioButton) findViewById(checkedId);
mtext = rb.getText().toString();
switch(checkedId){
case R.id.radio0:
Log.i("log", mtext);
break;
case R.id.radio1:
Log.i("log", mtext);
break;
default:
break;
}
}
}
<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.test_radio_group.MainActivity" >
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:orientation="horizontal"
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>