Android—自定义开关按钮实现

我们在应用中经常看到一些选择开关状态的配置文件,做项目的时候用的是android的Switch控件,但是感觉好丑的样子…………

个人认为还是自定义的比较好,先上个效果图:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKQAAACmCAIAAADbH7MdAAATQUlEQVR4nO2deXAk1X3Hew/WCy6OEKcCpDgDZRepVFwFwaFyx5WUkxBbI7G7wIJZlqOAwlyGcBjsYAowjr0GnCVc4bbXlDlWx0i7Wu3J6hrNjM6VRnNojr67Xx8zOno0PaNf/nij1rGwrKa7pRH9PvX++HVr+/V39dXv91739LymvvbaNGkeaVRrRxgoCjcSf7ljaoDwZWRwcPD4nVSS8GUnlUolk0mgKIoleAOgKIojeAOgKIrneUEQBEHgeb6C2ObhyxlXiYwVlEqJBG8AFEVJBG8AFEXJlSJJUsXHLjOrSCrGDcFlsxFCCCG8a6mxzcOXM64SGSsolUKVYnVU/aygVFmWRVHkOC6TyaRTqVQqla6UVDodSaY/itB39vJf75Qu7NQu7Mpe2JWbbdmLuvTLOiRfV+a9CB1hOGnh/xooikJV9tfnRrxSp5YkiWGYTDqdyWTwxS7HcVbwhfH8TYZl2xJcbQid2TlBdRWoQJHqmaGCx7VAkeo2N7SPX9nO/X44yQuiJYmY7WIsiiJN0zRN8xyHx+CKZYuy/GEKXR6cWBswqeAMFQQqdMIWnFnTbZ7XrrwUjnOCIM83m+A4kiRhp0VRtNmVjFBLRrkoMEn1nITN81tP6eyj2m/7Ry0NxGznkWWZZVmGYSRJst9bXETf7htf01Nags1zfhev+pTpi48hUsZdigVBoGlamK2fNmW/MqZtDBQs/04JwzePwTVR+PsInNYLVAjWhuAvh+EbQ7AmBFQIzu2Hbxwrx1QIvtI59ctARMaXXojgNDitLefswEjomsEJKjiDnVsfhocY6BmH9xU4lIP/leDsftgQho8VOJiD8waACsHWBOwU4SthK7lnrjmaZBiGmO08sizTNM3zvCO99fPosnDeSuu/i0JgAv56BDaE4YIB+ESF+zOwIQzNGgxOwrMcUCH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jG1YluV5HiGUna3nlqTKyzjhJNF1XVVV63kEWZZlWT6Z+CT/2aLVsfBCd8fLIGN2leKGYFLGqzp2tltbmU1YdRCzvQLJbA9BzPYQxGxvQcz2CiSzPQQx20MQs70FlcvlxsfHx8fH8fZSY5uHL2dcJTJWSmo5s6tN1ir6Da4iqaSMewhitregxislN1siqp9VJBXjhmAyZldp7Ea3QFFUVQlaRb+7VScbKOr/AU8HrTtCRFkjAAAAAElFTkSuQmCC" alt="" />

实现过程:

1.准备开关不同状态的两张图片放入drawable中。

2.xml文件中添加代码:

    <ToggleButton
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@android:color/transparent"
android:button="@drawable/btn_backgrounds"
android:checked="false"
android:textOff=""
android:textOn="" />
android:button="@drawable/btn_backgrounds"是自己定义的android selector文件:
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/toggle_btn_on" />
<item android:drawable="@drawable/toggle_btn_off" />

3,之后在java文件中声明ToggleButton控件并且实例化,添加点击事件:

    /**
* 自己出创建的内部类,监听按钮点击事件
*
* @author cyf
*
*/
class MyOnCheckedChangeListener implements OnCheckedChangeListener { @Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) { if (arg1) {
// 开
} else {
// 关
} } }

4.添加监听:

switch1.setOnCheckedChangeListener((OnCheckedChangeListener) new MyOnCheckedChangeListener());

笔记备忘一下,这个没有Switch的滑动效果~~~

 
上一篇:IE兼容性视图设置


下一篇:Android开发之sharedpreferences 详解