您的位置:首页 > 移动开发 > Android开发

Android开发RadioButton使用方法

2015-10-12 22:11 609 查看
如何使用RadioButton(单选按钮)?

RadioButton需要放在RadioGroup中组成一组单选框,组内的单选框是互斥的选中一个后,之间选中的单选框自动变为不选中。

下面代码添加了一个单选按钮组,让用户选择性别,点击确定按钮可以显示选中的单选按钮

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

    <!-- 创建单选按钮组 -->

    <RadioGroup

        android:id="@+id/radioGroup1"

        android:orientation="horizontal" <!-- 组内单选按钮排列方向 horizontal:水平排列 Vertical:垂直排列 -->

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true" >

        

        <!-- 定义单选按钮 -->

        <RadioButton

            android:id="@+id/rdMale"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:checked="true" <!-- 表示该单选按钮默认为选中 -->

            android:text="@string/male" />

        

        <RadioButton

            android:id="@+id/rdFemale"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="@string/female" />

    </RadioGroup>

    <TextView

        android:id="@+id/textView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerVertical="true"

        android:layout_toStartOf="@+id/radioGroup1"

        android:text="@string/sex" />

    <Button

        android:id="@+id/btnOk"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignBaseline="@+id/textView1"

        android:layout_alignBottom="@+id/textView1"

        android:layout_toEndOf="@+id/radioGroup1"

        android:text="@string/ok" />

</RelativeLayout>

在MainActivity中添加按钮btnOk的单击事件显示用户选中的性别

//获取确定按钮引用,为按钮添加单击事件的监听

Button btnOk=(Button)findViewById(R.id.btnOk);
btnOk.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

//获取RadioGroup组件的引用
RadioGroup radioGrp=(RadioGroup)findViewById(R.id.radioGroup1);
//获取当前选中的单选按钮的ID

int id = radioGrp.getCheckedRadioButtonId();

if(id != -1){//id=-1表示未选中任何单选按钮

//显示选中按钮的信息
RadioButton rdBtn=(RadioButton)findViewById(id);
Toast.makeText(MainActivity.this, "性别:"+rdBtn.getText(), Toast.LENGTH_SHORT).show();
}
}

});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息