安卓学习之路7之插件ToggleButton实现开关效果

来源:互联网 发布:开源snmp网络管理软件 编辑:程序博客网 时间:2024/06/05 03:35
ToggleButton
1.什么是ToggleButton:
  ToggleButton有两种状态:选中和未选中状态
  并且需要为不同的状态设置不同的显示文本
2.ToggleButton属性:
  android:checked="true"
  android:textOff="关"  //文字可自定义显示内容
  android:textOn="开"
3.使用ToggleButton按钮实现开关效果(事先放on和off两张图片在drawable中)
(1)先在xml中设置ToggleButton和ImageView
    <ToggleButton
        android:checked="false"    //这是是默认的,这里写明只是为了提醒而已;对应的是textOff
        android:textOn="开"
        android:textOff="关"
        android:id="@+id/toggleButton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/off"
/>
(2)在java中初始化这两个控件,再用监听器实现开关效果
   1.初始化控件
private ToggleButton tb;
private ImageView img;


        tb = (ToggleButton) findViewById(R.id.toggleButton1);
        img = (ImageView) findViewById(R.id.imageView1);
   2.给当前的tb设置监听器
tb.setOnCheckedChangeListener(this);


//这时鼠标指向MainActivity,补全onCheckedChanged函数
public class MainActivity extends Activity implements OnCheckedChangeListener{


   3.这是补全的函数再进行修改
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// 当tb被点击的时候,当前的方法会执行
/*
* buttonView---代表被点击控件的本身
* isChecked---代表被点击的控件的状态

* 当点击这个tb的时候,更换img的背景
*/
img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);


ToggleButton关效果图

}


ToggleButton开效果图


0 0
原创粉丝点击