03 CheckBox 复选框
五 CheckBox 复选框
>概念:可以从一个集合选项中选择一个或者多个选项
>属性:checked 选择状态
>使用:
>方式一:使用onclickListner 监听事件(点击事件)
>方式二:使用OnCheckedChangeListener (CompleButton) 状态改变的监听
如果有全选的:全选的按钮的监听必须用onclickListner 监听事件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <CheckBox android:id="@+id/sleep" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="睡觉" /> <!--android:checked="true"默认选中 --> <CheckBox android:id="@+id/eat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="吃饭" /> <CheckBox android:id="@+id/all" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="全选" /> </LinearLayout>
package com.fmy.a; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; public class MainActivity extends Activity { private CheckBox eat; private CheckBox sleep; private CheckBox all; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_textview); sleep = (CheckBox) findViewById(R.id.sleep); all = (CheckBox) findViewById(R.id.all); eat = (CheckBox) findViewById(R.id.eat); MyCheckedChangeListener myListener = new MyCheckedChangeListener(); eat.setOnCheckedChangeListener(myListener); sleep.setOnCheckedChangeListener(myListener); all.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { sleep.setChecked(true); eat.setChecked(true); } }); } class MyCheckedChangeListener implements OnCheckedChangeListener{ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (eat.isChecked()&&sleep.isChecked()) { all.setChecked(true); }else{ all.setChecked(false); } } } }