ToggleButton(开关按钮)是Android系统中比较简单的一个组件,是一个具有选中和未选择状态双状态的按钮,并且需要为不同的状态设置不同的显示文本。
ToggleButton常用的XML属性
属性名称 | 描述 |
android:disabledAlpha | 设置按钮在禁用时透明度。 |
android:textOff | 未选中时按钮的文本 |
android:textOn | 选中时按钮的文本 |
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent" android:background="#FFF5F5F5"
android:layout_height="fill_parent">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal">
<TextView android:textSize="14.0sp" android:id="@+id/tvSound" android:textColor="@android:color/black"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="已开启" />
<ToggleButton
android:id="@+id/tglSound" android:background="@drawable/selector_butn_toggle"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:checked="true" android:textOn="" android:textOff=""
android:text="" />
</LinearLayout>
</LinearLayout>
MainActivity.java:
package com.apkbus.toggle;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements OnCheckedChangeListener{
private ToggleButton mToggleButton;
private TextView tvSound;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题栏
setContentView(R.layout.main);
initView();//初始化控件方法
}
private void initView() {
mToggleButton = (ToggleButton) findViewById(R.id.tglSound); //获取到控件
mToggleButton.setOnCheckedChangeListener(this);//添加监听事件
tvSound = (TextView) findViewById(R.id.tvSound);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
tvSound.setText("已开启");
}else{
tvSound.setText("已关闭");
}
}
}
效果图:
![](http://www.apkbus.com/data/attachment/forum/201206/21/101541k43o45m9su2rvyo3.jpg)
![](http://www.apkbus.com/data/attachment/forum/201206/21/101720ltjvjvvttz56jf4s.jpg)
Demo下载地址:http://download.csdn.net/detail/u010963246/8941969