Android之简单改变按钮颜色方案

来源:互联网 发布:普吉岛打车软件 编辑:程序博客网 时间:2024/05/19 23:15

  前一段时间跟着大哥做项目,大哥让我给按钮背景添加颜色,然后点击变色,于是我就想到了button三态的变换方法,然而没有实现,反而出现了问题,今天就和大家说说,如何解决color设为背景颜色动态变色。

 一、当color设为字体颜色变化

  首先,我们在res下面创建一个drawable文件夹,然后在里面创建一个xml文件。这里我创建了一个叫text_color.xml文件。

在text_color.xml中

<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" >    <!-- 设置点击时字体颜色 -->    <item android:state_pressed="true" android:color="#ffff00"/>    <item android:state_selected="true" android:color="#ffff00"/>    <item android:state_focused="true" android:color="#ffff00"/>    <!-- 默认颜色 -->    <item android:color="#000000"/></selector>


然后我们只需要在要改变字体颜色的控件中设置这样一句话就可以了:

android:textColor="@drawable/text_color"

看一下效果图:


 是不是点击,颜色改变啦。

 二、当color设置为背景颜色变化。

 首先我们drawable文件夹里面创建一个xml文件。我这里创建了background_color.xml文件。

在background_color.xml文件中:

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <!-- 设置点击时颜色背景 -->    <item android:drawable="@drawable/btn_focused" android:state_focused="true"/>    <item android:drawable="@drawable/btn_focused" android:state_pressed="true"/>    <item android:drawable="@drawable/btn_focused" android:state_selected="true"/>    <!-- 设置默认时颜色背景 -->    <item android:drawable="@drawable/btn_normal"/></selector>
细心的小伙伴会发现,这里不是用的android:color而是用的android:drawable,如果这里设置为android:color,就会报错,这里必须是android:drawable

然后我们只需在values文件夹下面的color.xml文件中,把我们要使用的颜色这样设置就可以使用了:

<?xml version="1.0" encoding="utf-8"?><resources>    <drawable name="btn_focused">#ff0000</drawable>    <drawable name="btn_normal">#00ff00</drawable></resources>
把颜色设为drawable这种形式就可以了,这里drawable是用来填充矩形区域(圆角可以有);然后在需要设置的控件上添加这句话:

android:background="@drawable/background_color"

效果图如下:

简单改变按钮的方案就是这样。如有疑问可以留言给我,技术交流~~~

项目代码:

点击打开链接


4 0
原创粉丝点击