状态开关按钮(ToggleButton)与开关(Switch)都是继承Button的。
它们支持Button的各种属性。
它们常用在切换程序中的某种状态。
特有属性:
android:textOff 设置当前按钮关闭时显示的文本
android:textOn 设置当前按钮打开时显示的文本
android:thumb 使用自定义的Drawable绘制开关按钮(switch特有的)
package com.xspacing.togglebuttonandswitch;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
ToggleButton tb = (ToggleButton) findViewById(R.id.main_toggle);
Switch mSwitch = (Switch) findViewById(R.id.swich);
tb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String str = null;
str = isChecked ? "开关开启" : "开关关闭";
Toast.makeText(getApplicationContext(), str, 0).show();
}
});
mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String str = null;
str = isChecked ? "开关开启" : "开关关闭";
Toast.makeText(getApplicationContext(), str, 0).show();
}
});
}
}
<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:orientation="vertical"
tools:context="com.xspacing.togglebuttonandswitch.MainActivity" >
<ToggleButton
android:id="@+id/main_toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="off"
android:textOn="on" />
<Switch
android:id="@+id/swich"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>