ToggleButton
1.什么是ToggleButton
两种状态:选中觉未选中状态
并且为不同状态设置不同的显示文本。
2.ToggleButton属性
android:checked="true"
android:textOff="关"
android:textOn="开"
通过setOnCheckChangeListener设置ToggleButton监听
通过textOn设置选中状态的对应文本,textOff设置未选中状态的对应文本
默认checked=“false”
package com.example.togglebutton; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.ToggleButton; public class MainActivity extends Activity implements OnCheckedChangeListener { private ToggleButton tbButton; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化控件 tbButton = (ToggleButton) findViewById(R.id.toggleButton1); imageView = (ImageView) findViewById(R.id.imageView1); // 给当前的tbButton设置监听器 tbButton.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { /* * 当tbButton被点击的时候,当前的方法会被执行 buttonView-------------代表的是被点击控件的本身 * isChecked----------------代表被点击控件的状态 * * 当点击这个tbButton的时候,更换imageView的背景 */ tbButton.setBackgroundResource(isChecked ? R.drawable.on : R.drawable.off); } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_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="fill_parent" android:layout_height="200dp" android:background="@drawable/off" /> </LinearLayout>