1 什么是ToggleButton
ToggleButton是一种只有两面选择的控件off或者on类似于开关它还有一个兄弟即Switch(注意首字母大写,不要与关键字switch混淆)
下图中从左到右 分别为ToggleButton的on状态,ToggleButtono的off状态,Switch的on状态 ,switch的off状态
2 怎么用
下面分别定义ToggleButton与Switch
1)ToggleButton:
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="开"
android:textOff="关"
/>
2)Switch
<Switch
android:id="@+id/switch01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="开灯"
android:textOff="关灯"
android:checked="true"
android:layout_below="@id/toggleButton1"
/>
定义完了上面的两个组件就可以在虚拟机上显示了,结果如下:
3)添加事件处理方法
一丶实现接口
实现android.widget.CompoundButton.OnCheckedChangeListener这个接口,在create中获取相关的Id并且注册了监听器后重写父类的方法:
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//第一个参数为当前的组件,第二个为当前组件是否选择
ToggleButton toggleButton=(ToggleButton)buttonView;
boolean on=toggleButton.isChecked();
if(on){
Toast.makeText(this, "开灯", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "关灯", Toast.LENGTH_SHORT).show();
}
}
二丶自定义方法
需要在最开始定义ToggleButton与Switch的xml文件中添加 android: android:onClick="" 二者都实用
引号里面的就是我们自定义的事件处理方法的名称 特别注意该方法必须是public返回void 并且只接收一个View参数 我以Switch为例:
android:onClick="onSwitchClick"
public void onSwitchClick(View v){
boolean on=((Switch)v).isChecked();
if(on){
Toast.makeText(this, "开灯", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "关灯", Toast.LENGTH_SHORT).show();
}
}
效果与上面的一样,至此基本的ToggleButton已经会用了 但是不知道大家有没有发现ToggleButton与Switch都太丑了
3自定义ToggleButton
1)原料 on图片和off图片
2)创建自己的selector
在res文件夹下创建一个drawable文件夹然后把上面的两张图片复制到里面去,创建一个selector xml文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/on_button" android:state_checked="true" />
<item android:drawable="@drawable/off_button" android:state_checked="false" />"
</selector>
3)修改style 在res/values/styles.xml文件夹下添加如下代码:(item中的那个值是selector xml文件的名字,让系统风格为我自己定义的)
<style name="MyToggleButton" parent="@android:style/Widget.CompoundButton">
<item name="android:button">@drawable/my_togglebutton_style</item>
</style>
4)创建一个自己风格的ToggleButton
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
style="@style/MyToggleButton"
android:textOn=""
android:textOff=""
android:checked="true"
android:onClick="onToggleButtonClick"/>
5)添加事件处理方法
public void onSwitchClick(View v){
boolean on=((Switch)v).isChecked();
if(on){
Toast.makeText(this, "开灯", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "关灯", Toast.LENGTH_SHORT).show();
}
}