基本可用的自定义按钮实现

在前面几篇文章中做了一些尝试,但是还无法直接用于生产环境。现在基本实现了一个可正式使用的自定义按钮。

image  image

可以看到选中后变色,而且下面的视图也相应变化,起到类似Tab的效果。

另外,用手指触摸在按钮上,也会有颜色的变化。

原来想,如果要实现touch而界面变色要实现OnTouchLisnter的,其实不用。只需为按钮设置background即可,在布局文件中,比如:

<com.easymorse.textbutton.TextButton android:id="@+id/b2"
            android:layout_width="fill_parent" android:layout_height="fill_parent"
            android:clickable="true" android:layout_weight="1" android:text="电视"
            android:gravity="center_vertical|center_horizontal"
           android:background="@drawable/button" android:focusable="true" />

另外要设置clickable和focusable为true,这里的background属性指向的是一个配置文件,drawable/button.xml:


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:constantSize="true">
    <item android:state_focused="true">
        <shape>
            <gradient android:startColor="#FFE5CF33" android:endColor="#FFF1E7A2"
                android:angle="90.0">
            </gradient>
        </shape>

这个文件中可定义焦点进入视图,或者手指压在视图上的颜色,这里使用了渐变色。

选中某个按钮,颜色变深,只需让该按钮enable是false,即:

button.setEnabled(false);

颜色就会自动变深,因为在drawable/button.xml文件中已经定义。相反,可将其他按钮设置为true即可。

这里把按钮文字颜色都设置为白色了(#ffffffff),如果不设置,选中按钮后,系统默认是深色的,看起来不美观。也可以按照自定义视图中使用自定义变量中的做法,自定义选中和不选中时的文字颜色。

源代码见:

http://easymorse.googlecode.com/svn/tags/textButton-0.2.0/

PDF格式打印機    发送文章为PDF   

这篇文章上的评论的 RSS feed TrackBack URI

Leave a Reply