风格化的 Toggle Buttons

来源:互联网 发布:手机淘宝 怎么开店 编辑:程序博客网 时间:2024/05/17 02:42

目标:

 Android到默认UI比iOS到默认UI在美观程度上还是有一定到差距的,我们希望能够美化UI,并且替换掉系统默认的UI风格,使得程序在使用这些UI的时候都默认使用我们自定义到UI。本文以ToggleButton为例,介绍如何使用,下图是效果图。




步骤:

1、设置XML属性
我们需要设置ToggleButton的背景,以及当ToggleButton为on或者off时到状态图。

首先,我们设置ToggleButton的背景,建立 /res/drawable/btn_toggle_bg.xml

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <layer-list xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <item android:id="@+android:id/background" android:drawable="@android:color/transparent" />  
  4.     <item android:id="@+android:id/toggle" android:drawable="@drawable/btn_toggle" />  
  5. </layer-list>  
在这里,我们使用layer-list把ToggleButton分成2个图层,底层是背景(设置成透明),顶层是selector效果图


接下来,设置ToggleButton的on和off的selector效果图:

建立/res/drawable/btn_toggle.xml

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <item android:state_checked="false" android:drawable="@drawable/btn_toggle_no" />  
  4.     <item android:state_checked="true" android:drawable="@drawable/btn_toggle_yes" />  
  5. </selector>  

使用到以下两张图,也可通过以下链接查找http://bit.ly/pn5dmA

    
到此,我们已经把ToggleButton的效果已经制作完毕.


2、设置Style & Theme

ToggleButton到效果图已经制作完毕,接下来,我们就要把这种效果设置成一种统一的风格,否则我们在使用的时候必须每次都得显示指定这种风格,在这里,即:在声明ToggleButton的时候,每次都得指定android:background="@drawable/btn_toggle_bg"。

我们希望达到到效果是,当我们每次使用ToogleButton的时候,默认就是使用我们所设置的风格。在此之前,最好先阅读下android自带到文档:basics of creating Android themes,对style和theme有一定的了解。


接下来,建立/res/drawable/themes.xml文件

[html] view plaincopy
  1. <style name="Widget.Button.Toggle" parent="android:Widget">  
  2.     <item name="android:background">@drawable/btn_toggle_bg</item>  
  3.     <item name="android:textOn">@null</item>  
  4.     <item name="android:textOff">@null</item>  
  5.     <item name="android:clickable">true</item>  
  6.     <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>  
  7. </style>  
在这里,要把textOn和textOff的属性设置为null,否则,系统会在按钮上显示文字,这个可根据使用情况而定。

然后,把该风格设置成主题

[html] view plaincopy
  1. <style name="YourThemeName" parent="@android:Theme.Black">  
  2.     <!-- 告诉Android当创建ToggleButton的时候使用自定义风格 -->  
  3.     <item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>  
  4.     <!-- 在这里可以添加更多的选项... -->  
  5. </style>  


之后,只需要在AndroidManifest.xml的<application>标签里设置主题即可(android:theme="@style/YourThemeName")

3、注意事项

  • <重要>为了提供更通用到效果,应该把图片设置成.9.png格式,使图片可扩展
  • 很多人都以疑问,到底如何知道这些控件或者主题到属性? 这些都在Android到源代码里面可以找到,具体位置在\base\core\res\res\values\里
  • 项目源码下载:http://download.csdn.net/source/3470224
转载地址:http://blog.csdn.net/billpig/article/details/6634481