[Android]笔记10-单选按钮和复选框的功能与用法
16lz
2021-01-24
单选钮(RadioButton)、复选框(CheckBox)、状态开关按钮(ToggleButton)和开关(Switch)是用户界面中最普遍的UI组件,他们都继承了button类,因此都可直接使用button支持的各种属性和方法。
RadioButton、Checkbox与普通按钮不同的是,他们多了一个可选中的功能,因此RadioButton、Checkbox都额外指定一个checked属性,该属性用于指定RadioButton、Checkbox初始时是否被选中
XML:
<?xml version="1.0" encoding="utf-8"?><TableLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.dezai.checkbuttontest.MainActivity"><TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="性别:"/> <RadioGroup android:id="@+id/rg" android:orientation="horizontal" android:layout_gravity="center_horizontal"> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/male" android:text="男" android:checked="true"/> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/female" android:text="女" /> RadioGroup>TableRow><TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="喜欢的颜色:"/><LinearLayout android:layout_gravity="center_horizontal" android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="wrap_content"> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="红色" android:checked="true"/> <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="绿色"/>LinearLayout>TableRow> <TextView android:id="@+id/show" android:layout_height="wrap_content" android:layout_width="wrap_content"/>TableLayout>
java
package com.dezai.checkbuttontest;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.RadioGroup;import android.widget.TextView;public class MainActivity extends AppCompatActivity { RadioGroup rg; TextView show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取界面上rg/show两个组件 rg=(RadioGroup)findViewById(R.id.rg); show=(TextView) findViewById(R.id.show); //为RadionGroup 组件的OnCheckedChanged事件绑定事件监听器 rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup group,int checkedId){ // String tip=checkedId==R.id.male?"你的性别是男人":"你的性别是女人"; show.setText(tip); } }); }}
来自:疯狂讲义
更多相关文章
- UI组件之 ProgressBar及其子类(一)ProgressBar进度条的使用
- :Android和j2me的初级对比
- Android应用基础知识
- android:windowSoftInputMode属性详解以及editText监听键盘回车
- Android知识巩固—四大组件能否开多进程
- android布局属性使用说明和一些开发经验
- Android下affinities和任务(task)
- Unity与Android之间的交互之AndroidManifest
- 解决使用Android(安卓)emulator(模拟器)无法上网的现象