单选钮(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);
}
});
}
}
来自:疯狂讲义
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。