本期先来学习Button的两个子控件,无论是单选还是复选,在实际开发中都是使用的较多的控件,相信通过本期的学习即可轻松掌握。
一、CheckBox
CheckBox(复选框)是Android中的复选框,主要有两种状态:选中和未选中。通过isChecked方法来判断是否被选中,当用户单击时可以在这两种状态间进行切换,会触发一个OnCheckedChange事件。
接下来通过一个简单的示例程序来学习CheckBox的使用用法。
同样使用WidgetSample工程,在app/main/res/layout/目录下创建一个checkbox_layout.xml文件,然后在其中填充如下代码片段:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择喜欢的城市"/>
<CheckBox
android:id="@+id/shanghai_cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上海"
android:checked="true"/>
<CheckBox
android:id="@+id/beijing_cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="北京"/>
<CheckBox
android:id="@+id/chongqing_cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="重庆"/>
</LinearLayout>
然后修改一下app/src/java/MainActivity.java文件中加载的布局文件为新建的checkbox_layout.xml文件。为了监听三个复选框的操作事件,在Java代码中分别为其添加事件监听器,具体代码如下:
package com.jinyu.cqkxzsxy.android.widgetsample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private CheckBox mShanghaiCb = null; // 上海复选框
private CheckBox mBeijingCb = null; // 北京复选框
private CheckBox mChongqingCb = null; // 重庆复选框
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkbox_layout);
// 获取界面组件
mShanghaiCb = (CheckBox) findViewById(R.id.shanghai_cb);
mBeijingCb = (CheckBox) findViewById(R.id.beijing_cb);
mChongqingCb = (CheckBox) findViewById(R.id.chongqing_cb);
// 为上海复选框绑定OnCheckedChangeListener监听器
mShanghaiCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
// 提示用户选择的城市