ToggleButton的使用解析
1两种状态:
选中和未选中状态,并且需要为不同的状态设置不同的显示文本
2.属性:
Android:checked=”true”
Android:textOff=”显示文本1”
Android:textOn=”显示文本2”
3.使用样例(通过ToggleButton控制ImageView显示不同的图片)
a.布局文件activity_main代码
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ToggleButton android:id="@+id/toggleButton1" android:layout_width="match_parent" android:layout_height="wrap_content" android:checked="false" android:textOff="关" android:textOn="开" /> <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/off" /> </LinearLayout>
b.MainActivity代码
public class MainActivity extends ActionBarActivity implements OnCheckedChangeListener { private ToggleButton tb; private ImageView img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tb=(ToggleButton) findViewById(R.id.toggleButton1); img=(ImageView) findViewById(R.id.imageView1); tb.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton arg0, boolean isChecked) { img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off); } }
c.方法总结
setOnCheckedChangeListener ToggleButton监听事件的方法,此样例中是通过实现接口的方式去实现事件监听的。
setBackgroundResource方法改变ImageView的Background,显示不同的图片。
d.运行结果
点击开关按钮时,将在下面两个画面进行切换