代码如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<CheckBox
android:id="@+id/onecheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="学习"
/>
<CheckBox
android:id="@+id/twocheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="睡觉"
/>
<CheckBox
android:id="@+id/therecheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="吃饭"
/>
<CheckBox
android:id="@+id/allcheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打代码"
/>
</LinearLayout>
package com.example.tectcheck;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class MainActivity extends Activity {
private CheckBox onecheck;
private CheckBox twocheck;
private CheckBox therecheck;
private CheckBox allcheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onecheck=(CheckBox)findViewById(R.id.onecheck);
twocheck=(CheckBox)findViewById(R.id.twocheck);
therecheck=(CheckBox)findViewById(R.id.therecheck);
allcheck=(CheckBox)findViewById(R.id.allcheck);
AllCheckListener listener=new AllCheckListener();
allcheck.setOnCheckedChangeListener(listener);
}
class AllCheckListener implements OnCheckedChangeListener{
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// 第一种方法
// if(isChecked){
// onecheck.setChecked(true);
// twocheck.setChecked(true);
// therecheck.setChecked(true);
// }else{
// onecheck.setChecked(false);
// twocheck.setChecked(false);
// therecheck.setChecked(false);
// }
//第二种方法
onecheck.setChecked(isChecked);
twocheck.setChecked(isChecked);
therecheck.setChecked(isChecked);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
效果图