Android的RadioButton和checkBox的用法-android学习之旅(十九)

时间:2023-03-09 05:02:59
Android的RadioButton和checkBox的用法-android学习之旅(十九)

RadioButton和checkBox简介

单选按钮(RadioButton)和复选框(CheckBox)都继承了Button,因此属性的设置和Button差不多,只是加了一个android:chencked属性。

用来设置是否被选中。

RadioButton和checkBox的区别

前者如果一组只能只能选中一个,一次通常会与RadioGroup一块使用,后者没有限制。

实例

<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:orientation="vertical">
  <TableRow android:layout_width="wrap_content"
      android:layout_height="wrap_content">
      <TextView android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="性别:"
          android:textSize="16px"/>
      <RadioGroup
          android:orientation="horizontal"
          android:id="@+id/rg"
          android:layout_gravity="center_horizontal"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
          <RadioButton
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="男"
              android:checked="true"/>
          <RadioButton
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="女"
              />
          </RadioGroup>
  </TableRow>
    <TableRow android:layout_height="wrap_content"
        android:layout_width="wrap_content">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="喜欢的颜色"
            android:textSize="16px"/>
        <CheckBox android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="红色"/>
        <CheckBox android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="蓝色"/>
        <CheckBox android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="绿色"/>
    </TableRow>
    <TableRow android:layout_height="match_parent"
        android:layout_width="match_parent">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="show"/>
    </TableRow>
</LinearLayout>

效果图

Android的RadioButton和checkBox的用法-android学习之旅(十九)