Android控件之RadioGroup与RadioButton(单选控件)

一、RadioGroup与RadioButton

  1、什么是RadioGroup:

    RadioButton的一个集合,提供多选机制

  2、什么是RadioButton:

    RadioButton包裹在RadioGroup中,RadioGroup表示一组RadioButton,下面可以有很多个RadioButton,但只能有一个被选中

  3、RadioGroup属性:

    android:orientation——  设置RadioGroup中RadioButton以什么形式排列(有两个值分别是:horizontal(水平排布)和 vertical(垂直排布))

 

 

 

二、代码演示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

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

        <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>

</LinearLayout>
package com.muke.textview_edittext;

import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.app.Activity;


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);
        
        //第二步:实现RadioGroup的监听事件
        rg.setOnCheckedChangeListener(this);
        
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        //checkedId表示被选中的那个RadioButton的id
        switch(checkedId){
        case R.id.radio0:
            System.out.println("男被选中");
            break;
        case R.id.radio1:
            System.out.println("女被选中");
            break;
        }
    }
        
}

 

posted @ 2015-07-20 23:26  胡椒粉hjf  阅读(2098)  评论(0编辑  收藏  举报