Android成长日记-使用ToggleButton实现灯的开关

案例演示

clip_image002 clip_image004

此案例实现思路:通过ToggleButton控件,ImageView控件实现

---xml代码:

<!-- textOn:true textOff:falase[s1] -->

<ToggleButton

android:id="@+id/toggleB utton1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:checked="false[s2] "

android:textOn="[s3] "

android:textOff="" />

<ImageView

android:id="@+id/imageView1"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@drawable/off" />

----java代码:

1. 正如普通控件的使用思路

(首先定义控件、初始化控件)

private ToggleButton tb;

private ImageView img;

tb=(ToggleButton) findViewById(R.id.toggleButton1);

img=(ImageView) findViewById(R.id.imageView1);

2. 设置控件的监听器

-----------------通过接口实现监听功能

--public class MainActivity extends Activity implements OnCheckedChangeListener()

--tb.setOnCheckedChangeListener(this);

--写出此接口所必须的方法

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

/*

* 当tb被点击时,当前方法被执行

* buttonView------代表被点击控件的本身

* isChecked-----代表被点击控件的状态

*

* 当点击这个tb的时候,更换img的背景

*/

img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off[s4] );

}


[s1]textOn:当按钮被点击

textOff:当按钮未被点击

[s2]此条语句可写可不写,表示现在的状态

[s3]设置文字状态

[s4]此处为条件语句

原文地址:https://www.cnblogs.com/boy1025/p/4302010.html