Android之单选按钮RadioGroup & RandioButton

在安卓APP中,单选按钮是很常见的一个控件,这里我们一起来学习一下吧。

RadioButton和RadioGroup的关系:

1、RadioButton表示单个圆形单选框,而RadioGroup是可以容纳多个RadioButton的容器

2、每个RadioGroup中的RadioButton同时只能有一个被选中

3、不同的RadioGroup中的RadioButton互不相干,即如果组A中有一个选中了,组B中依然可以有一个被选中

4、大部分场合下,一个RadioGroup中至少有2个RadioButton

5、大部分场合下,一个RadioGroup中的RadioButton默认会有一个被选中,并建议您将它放在RadioGroup中的起始位置


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"
    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.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="17dp" >

        <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="女" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="外星" />
    </RadioGroup>

</RelativeLayout>

Activity代码:

private RadioGroup radioGroup;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		radioGroup = (RadioGroup)findViewById(R.id.radioGroup1);
		radioGroup.check(R.id.radio1);
		RadioButton radioButton = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());
		
		Toast.makeText(getApplicationContext(), "您选择的性别是:"+radioButton.getText(), Toast.LENGTH_SHORT).show();
		
		radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
				//RadioButton radioButton = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());
				RadioButton radioButton = (RadioButton)findViewById(checkedId);
				Toast.makeText(getApplicationContext(), "您选择的性别是:"+radioButton.getText(), Toast.LENGTH_SHORT).show();
			}
		});
		
	}

 
 

猜你喜欢

转载自wangking717.iteye.com/blog/2240525