Android控件之ToggleButton的使用方法

<p>ToggleButton的状态只能是选中和未选中,并且需要为不同的状态设置不同的显示文本。</p><p>以下案例为ToggleButton的用法</p><p>目录结构</p><p><img src="/up_pic/201812/171045386496.png" title="171045386496.png" alt="1.png"/></p><p>main.xml布局文件</p><p>代码如下:</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:layout_height=&quot;fill_parent&quot;&gt; &lt;ImageViewandroid:id=&quot;@+id/imageView&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:src=&quot;@drawable/bulb_off&quot; android:layout_gravity=&quot;center_horizontal&quot;/&gt; &lt;ToggleButtonandroid:id=&quot;@+id/toggleButton&quot; android:layout_width=&quot;140dip&quot; android:layout_height=&quot;wrap_content&quot; android:textOn=&quot;开灯&quot; android:textOff=&quot;关灯&quot; android:layout_gravity=&quot;center_horizontal&quot;/&gt; &lt;/LinearLayout&gt;</pre><p>ToggleButtonActivity类</p><p>代码如下:</p><pre class="brush:java;toolbar:false">packagecom.ljq.tb; importandroid.app.Activity; importandroid.os.Bundle; importandroid.widget.CompoundButton; importandroid.widget.ImageView; importandroid.widget.ToggleButton; importandroid.widget.CompoundButton.OnCheckedChangeListener; publicclassToggleButtonActivityextendsActivity{ privateImageViewimageView=null; privateToggleButtontoggleButton=null; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); imageView=(ImageView)findViewById(R.id.imageView); toggleButton=(ToggleButton)findViewById(R.id.toggleButton); toggleButton.setOnCheckedChangeListener(newOnCheckedChangeListener(){ publicvoidonCheckedChanged(CompoundButtonbuttonView, booleanisChecked){ toggleButton.setChecked(isChecked); imageView.setImageResource(isChecked?R.drawable.bulb_on:R.drawable.bulb_off); } }); } }</pre><p>运行效果:</p><p><img src="/up_pic/201812/171045424916.png" title="171045424916.png" alt="2.png"/></p>
RangeTime:0.008128s
RangeMem:206.09 KB
返回顶部 留言