开关按钮,只有开和关两种状态,ToggleButton只能点击,Switch可以点击也可以按住滑块拖动。在XML文件中需要为它布置两个属性textOn和textOff分别表示开关状态显示的文字,当然也可以通过设置背景图片来使它摆脱Android原生样式,一般都是通过为其定制selector设置两个状态的两个图片来达到效果,如果给Switch设置背景将会为其中间的滑块设置背景。在Activity类文件中,通过isChecked方法判断是否开,通过setOnCheckedChangeListener()方法设置点击事件,通过setChecked()方法设置状态。
这里有一个开关按钮开关电灯的实例,通过点击ToggleButton和Switch更换图片达到效果,当然其中一个点击后必须改变另一个的状态保持和睦。
布局文件如下
<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:background="#000000"
android:orientation="vertical" >
<ImageView
android:id="@+id/iv_boo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/boo"
android:layout_gravity="center_horizontal"
android:alpha="1" />
<ToggleButton
android:id="@+id/tb_swich"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="关灯"
android:textOff="开灯"
android:layout_gravity="center_horizontal"
android:layout_marginTop="100dp"/>
<Switch
android:id="@+id/sw_swich"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="关灯"
android:textOff="开灯"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"/>
</LinearLayout>
MainActivity.class
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
ImageView ivBoo;
ToggleButton tbSwich;
Switch swich;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivBoo = (ImageView) findViewById(R.id.iv_boo);
tbSwich = (ToggleButton) findViewById(R.id.tb_swich);
swich = (Switch) findViewById(R.id.sw_swich);
tbSwich.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
tbSwich.setChecked(isChecked);
if(isChecked){
ivBoo.setImageResource(R.drawable.boolight);
swich.setChecked(true);
}
else{
ivBoo.setImageResource(R.drawable.boo);
swich.setChecked(false);
}
}
});
swich.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
swich.setChecked(isChecked);
if(isChecked){
ivBoo.setImageResource(R.drawable.boolight);
tbSwich.setChecked(true);
}
else{
ivBoo.setImageResource(R.drawable.boo);
tbSwich.setChecked(false);
}
}
});
}
}
效果如下