关键字:ischecked setOnCheckedChangeListener ToggleButton.OnCheckedChangeListener() onCheckedChanged
开关控件有两种
<ToggleButton
android:id="@+id/togglecheck"
android:textOff="关"
android:textOn="开"
/>
ToggleButton是一个图标每点击一次,开关转换一次
<Switch
android:id="@+id/swichcheck"
android:textOn="开"
android:textOff="关"
/>
Switch是一个图标分两节,点击或者按着滑动都可以转化
ischecked为true时,是开
mtoggleButton.setOnCheckedChangeListener(new ToggleButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean ischecked) {
if(ischecked){
Snackbar.make(compoundButton,"开",Snackbar.LENGTH_SHORT).show();
}else {
Snackbar.make(compoundButton,"关",Snackbar.LENGTH_SHORT).show();
}
}
});
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton compoundButton, boolean ischecked){
if(ischecked){
Snackbar.make(compoundButton,"开",Snackbar.LENGTH_SHORT).show();
}else{
Snackbar.make(compoundButton,"关",Snackbar.LENGTH_SHORT).show();
}
}
});
}
开关控件有两种
<ToggleButton
android:id="@+id/togglecheck"
android:textOff="关"
android:textOn="开"
/>
ToggleButton是一个图标每点击一次,开关转换一次
<Switch
android:id="@+id/swichcheck"
android:textOn="开"
android:textOff="关"
/>
Switch是一个图标分两节,点击或者按着滑动都可以转化
还是,如果你想用户知道自己到底是打开还是关闭,可以设定提醒
具体方法是
找到id
mtoggleButton= (ToggleButton) findViewById(R.id.togglecheck);
mSwitch= (Switch) findViewById(R.id.swichcheck);
设定改变与否监听
setOnCheckedChangeListener
监听改变
ToggleButton.OnCheckedChangeListener()//因为在onCheckedChanged方法里面,有两个属性CompoundButton,与boolean
CompoundButton是button类的父类,所以必须使
当发生改变时
ischecked为true时,是开
mtoggleButton.setOnCheckedChangeListener(new ToggleButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean ischecked) {
if(ischecked){
Snackbar.make(compoundButton,"开",Snackbar.LENGTH_SHORT).show();
}else {
Snackbar.make(compoundButton,"关",Snackbar.LENGTH_SHORT).show();
}
}
});
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton compoundButton, boolean ischecked){
if(ischecked){
Snackbar.make(compoundButton,"开",Snackbar.LENGTH_SHORT).show();
}else{
Snackbar.make(compoundButton,"关",Snackbar.LENGTH_SHORT).show();
}
}
});
}