获取RadioButton选中的值

<RadioGroup android:id="@+id/gender"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:orientation="horizontal">
        <RadioButton android:id="@+id/gender_male"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="男" android:checked="true"
            android:textSize="24dp" android:textColor="#000000"/>
        <RadioButton android:id="@+id/gender_female"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="女" android:checked="false" 
            android:layout_marginLeft="100dp" android:drawablePadding="10dp"
            android:textSize="24dp" android:textColor="#000000"/>
</RadioGroup>
public class TestActivity extends Activity {

    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		RadioGroup gender = (RadioGroup) findViewById(R.id.gender);
		final RadioButton male = (RadioButton) findViewById(R.id.gender_male);
		final RadioButton female = (RadioButton) findViewById(R.id.gender_female);
		gender.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId == male.getId()) {
					Toast.makeText(TestActivity.this, "male",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(TestActivity.this, "female",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
         }
}

猜你喜欢

转载自yeruowei.iteye.com/blog/1838774