<p>ToggleButton是android给我们提供的开关按钮,</p><p>有两种状态:选中和未选择状态。</p><p>以下是代码实例: main.xml</p><pre class="brush:xml;toolbar:false"><?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"android:layout_width="fill_parent"android:background="#FFF5F5F5"
android:layout_height="fill_parent">
<LinearLayoutandroid:layout_width="fill_parent"
android:layout_height="wrap_content"android:orientation="horizontal">
<TextViewandroid: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></pre><p></p><p>这是主MainActivity</p><pre class="brush:java;toolbar:false">
packagecom.apkbus.toggle;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.view.Window;
importandroid.widget.CompoundButton;
importandroid.widget.CompoundButton.OnCheckedChangeListener;
importandroid.widget.TextView;
importandroid.widget.ToggleButton;
publicclassMainActivityextendsActivityimplementsOnCheckedChangeListener{
privateToggleButtonmToggleButton;
privateTextViewtvSound;
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题栏
setContentView(R.layout.main);
initView();//初始化控件方法
}
privatevoidinitView(){
mToggleButton=(ToggleButton)findViewById(R.id.tglSound);//获取到控件
mToggleButton.setOnCheckedChangeListener(this);//添加监听事件
tvSound=(TextView)findViewById(R.id.tvSound);
}
@Override
publicvoidonCheckedChanged(CompoundButtonbuttonView,booleanisChecked){
if(isChecked){
tvSound.setText("已开启");
}else{
tvSound.setText("已关闭");
}
}
}</pre><p>这是效果图</p><p><img src="/up_pic/201812/171011348683.jpg" title="171011348683.jpg" alt="1.jpg"/></p><p><img src="/up_pic/201812/171011394361.jpg" title="171011394361.jpg" alt="2.jpg"/></p><p></p>