常用属性
<CheckBox android:id="@+id/cb_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="足球"
android:textSize="20dp"
android:layout_below="@+id/text"
android:layout_marginBottom="10dp"
/>
<CheckBox android:id="@+id/cb_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="篮球"
android:textSize="20dp"
android:layout_below="@+id/text"
android:layout_toRightOf="@+id/cb_1"
android:layout_marginBottom="10dp"
/>
<CheckBox android:id="@+id/cb_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="排球"
android:textSize="20dp"
android:layout_toRightOf="@+id/cb_2"
android:layout_below="@+id/text"
android:layout_marginRight="@+id/cb_2"
android:layout_marginBottom="10dp"
/>
<CheckBox android:id="@+id/cb_4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="网球"
android:textSize="20dp"
android:layout_below="@+id/text"
android:layout_marginRight="@+id/cb_3"
android:layout_toRightOf="@+id/cb_3"
android:layout_marginBottom="10dp"
/>
自定义样式
android:button="@drawable/bg_button"引用样式
监听事件
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class CheckBoxActivity extends AppCompatActivity {
private CheckBox cb1,cb2,cb3,cb4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box);
cb1=findViewById(R.id.cb_1);
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(CheckBoxActivity.this,isChecked?"1选中":"1未选中",Toast.LENGTH_SHORT).show();
}
});
cb2=findViewById(R.id.cb_2);
cb2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(CheckBoxActivity.this,isChecked?"2选中":"2未选中",Toast.LENGTH_SHORT).show();
}
});
cb3=findViewById(R.id.cb_3);
cb3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(CheckBoxActivity.this,isChecked?"3选中":"3未选中",Toast.LENGTH_SHORT).show();
}
});
cb4=findViewById(R.id.cb_4);
cb4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(CheckBoxActivity.this,isChecked?"4选中":"4未选中",Toast.LENGTH_SHORT).show();
}
});
}
}