preview
CheckBox就是复选框
两种状态:被选中(true),未被选中(false)
属性:android:checked=”false”——–决定它被选中与否
exercise
实现点击一个CheckBox后屏幕会显示该CheckBox的文字内容
layout
<!--默认android:checked="false",当然也可以写android:checked="true"进去,这样
Box刚开始就是被选中的状态-->
<CheckBox
android:text="CheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/checkBox" />
Activity
public class MainActivity extends AppCompatActivity {
private CheckBox ckBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ckBox= (CheckBox) findViewById(R.id.checkBox);
ckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//通过onCheckedChanged来监听CheckBox是否被选中,并把被选中的Box的文字信息显示出来
if(b){
String text=ckBox.getText().toString();
//被点中时显示CheckBox的文字内容
Toast.makeText(MainActivity.this,text,Toast.LENGTH_SHORT).show();
}
}
});
}
}