<p>ToggleButton是android给我们提供的开关按钮,</p><p>有两种状态:选中和未选择状态。</p><p>以下是代码实例: main.xml</p><pre class="brush:xml;toolbar:false">&lt;?xmlversion=&quot;1.0&quot;encoding=&quot;utf-8&quot;?&gt; &lt;LinearLayoutxmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:orientation=&quot;vertical&quot;android:layout_width=&quot;fill_parent&quot;android:background=&quot;#FFF5F5F5&quot; android:layout_height=&quot;fill_parent&quot;&gt; &lt;LinearLayoutandroid:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;wrap_content&quot;android:orientation=&quot;horizontal&quot;&gt; &lt;TextViewandroid:textSize=&quot;14.0sp&quot;android:id=&quot;@+id/tvSound&quot;android:textColor=&quot;@android:color/black&quot; android:layout_width=&quot;wrap_content&quot;android:layout_height=&quot;wrap_content&quot; android:text=&quot;已开启&quot;/&gt; &lt;ToggleButton android:id=&quot;@+id/tglSound&quot;android:background=&quot;@drawable/selector_butn_toggle&quot; android:layout_width=&quot;wrap_content&quot;android:layout_height=&quot;wrap_content&quot; android:checked=&quot;true&quot;android:textOn=&quot;&quot;android:textOff=&quot;&quot; android:text=&quot;&quot;/&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt;</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(&quot;已开启&quot;); }else{ tvSound.setText(&quot;已关闭&quot;); } } }</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>
返回顶部 留言