Android基本组件之单选按钮和复选框(自用)

来源:互联网 发布:生物医学数据库使用 编辑:程序博客网 时间:2024/05/16 08:52

单选按钮和复选框都是继承普通按钮,因此它们都可以直接使用普通按钮支持的各种属性和方法。

单选按钮由

<RadioButton    android:text="显示文本"    android:id="@+id/ID号"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:checked=[true|false]//true为被选中状态>    </RadioButton>

定义

RadioButton通常要与RadioGroup一起使用,RadioGroup的常用属性与布局管理器常用属性一样,都需要定义android:orientation

这里摘取《Android从入门到精通》的一个例子
layout里面的代码:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal"     android:layout_width="wrap_content"    android:layout_height="wrap_content"     android:background="@drawable/background">    <TextView         android:layout_width="wrap_content"        android:layout_height="wrap_content"         android:text="性别:"        android:height="50px" />    <RadioGroup         android:id="@+id/radioGroup1"        android:orientation="horizontal"         android:layout_width="wrap_content"         android:layout_height="wrap_content">        <RadioButton             android:layout_height="wrap_content"             android:id="@+id/radio0"             android:text="男"             android:layout_width="wrap_content"             android:checked="true"/>//这里不需要</RadioButton>        <RadioButton             android:layout_height="wrap_content"             android:id="@+id/radio1"             android:text="女"             android:layout_width="wrap_content"/>    </RadioGroup>    <Button android:text="提交" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button></LinearLayout>

在activity中

final RadioGroup sex = (RadioGroup) findViewById(R.id.radioGroup1); //获取单选按钮组        //为单选按钮组添加事件监听        sex.setOnCheckedChangeListener(new OnCheckedChangeListener() {            @Override            public void onCheckedChanged(RadioGroup group, int checkedId) {                RadioButton r = (RadioButton) findViewById(checkedId);  //获取被选择的单选按钮                Log.i("单选按钮", "您的选择是:" + r.getText());            }        });

复选框
在默认情况下,复选框显示为一个方块图标,并且在该图标旁边放置一些说明性文字。与单选按钮唯一不同的是,复选框可以进行多选设置,每一个复选框都提供“选中”和“不选中”两种状态。在Android中,可以使用2种方式向屏幕中添加复选框,一种是通过在XML布局文件中使用< CheckBox>标记添加,另一种是在JAVA文件中,通过new关键字创建。跟单选按钮差不多操作

0 0
原创粉丝点击