一、
1.checkbox_layout.xml
<?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/checkAllId"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="全选"/>
<CheckBox
android:id="@+id/eatId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff0000"
android:textSize="50dp"
android:text="吃饭"/>
<CheckBox
android:id="@+id/sleepId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0000ff"
android:textSize="50sp"
android:text="睡觉"/> </LinearLayout>
2.MainActivity.java
@SuppressLint("NewApi")
public class MainActivity extends ActionBarActivity { private TextView textView;
private Button button;
int count = 0;
//CheckBox
private CheckBox eateBox;
private CheckBox sleepBox;
private CheckBox checkAll; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkbox_layout); //checkbox
eateBox = (CheckBox) findViewById(R.id.eatId);
sleepBox = (CheckBox) findViewById(R.id.sleepId);
checkAll = (CheckBox) findViewById(R.id.checkAllId);
OnBoxChickListener boxListener = new OnBoxChickListener();
// eateBox.setOnClickListener(boxListener);
// sleepBox.setOnClickListener(boxListener);
OnBoxChangeListener changeListener = new OnBoxChangeListener();
eateBox.setOnCheckedChangeListener(changeListener);
sleepBox.setOnCheckedChangeListener(changeListener);
checkAll.setOnCheckedChangeListener(changeListener); // setContentView(R.layout.dpsp_layout);
// setContentView(R.layout.activity_main);
//setContentView(R.layout.first_layout); /*TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Hello View");
textView.setBackgroundColor(Color.CYAN); button = (Button) findViewById(R.id.button);
ButtonListener buttonListener = new ButtonListener();
button.setOnClickListener(buttonListener);*/ } class OnBoxChickListener implements OnClickListener { @Override
public void onClick(View v) {
System.out.println(v.getId());
CheckBox box = (CheckBox) v;
System.out.println(box.isChecked());
System.out.println("CheckBox is clicked");
} } class OnBoxChangeListener implements OnCheckedChangeListener { @Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(R.id.eatId == buttonView.getId()) {
System.out.println("eatButton");
} else if(R.id.sleepId == buttonView.getId()) {
System.out.println("sleepButton");
} else if(R.id.checkAllId == buttonView.getId()) {
eateBox.setChecked(isChecked);
sleepBox.setChecked(isChecked);
}
System.out.println(isChecked ? "选中" : "取消");
} }