Android 使用RadioGroup和RadioButton实现单选效果

RadioButton和CheckBox的区别:CheckBox选中之后可以直接取消,RadioButton选中之后不能直接取消,所以一般情况下不建议单独使用。
1.RadioGroup:
RadioButton的一个集合,提供多选一机制。
2.属性:
android:orientation ("vertical"--垂直排布;"horizontal"--水平排布)
决定当前RadioGroup中RadioButton以什么形式排列

使用RadioButton和RadioGroup实现多选一效果
监听可以使用RadioGroup的OnClickeListener,也可以使用RadioButton的OnCliekedChangeListener。

样例程序包含一个包含两个RadioButton的RadioGroup和一个TextView,TextView会实时显示选中的性别信息。

package com.example.radiogroupradiobutton;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
    
    private RadioGroup radioGroup;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        textView = (TextView) findViewById(R.id.textView1);

        radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
        radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                case R.id.radio0: textView.setText("选中:男"); break;
                case R.id.radio1: textView.setText("选中:女"); break;
                default: textView.setText("未选中"); break;
                }
            }
            
        });
    }
    
}
MainActivity.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android1="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:orientation="vertical"
    >

    <RadioGroup
        android:orientation="vertical"
        android1:id="@+id/radioGroup1"
        android1:layout_width="wrap_content"
        android1:layout_height="wrap_content" >

        <RadioButton
            android1:id="@+id/radio0"
            android1:layout_width="wrap_content"
            android1:layout_height="wrap_content"
            android1:checked="true"
            android1:text="男" />

        <RadioButton
            android1:id="@+id/radio1"
            android1:layout_width="wrap_content"
            android1:layout_height="wrap_content"
            android1:text="女" />

    </RadioGroup>

    <TextView
        android1:id="@+id/textView1"
        android1:layout_width="wrap_content"
        android1:layout_height="wrap_content"
        android1:text="选中:男" />

</LinearLayout>
activity_mail.xml

效果:

posted @ 2016-04-17 22:02  月光诗人  阅读(1173)  评论(0编辑  收藏  举报