您的位置:首页 > 移动开发 > Android开发

Android Button点击效果(按钮背景变色、文字变色)

2017-09-15 13:25 477 查看
我们做应用有时需要点击按钮时的文字颜色变换效果,目前发现两种解决方案:第一用图片,如果出现的地方比较多,那么图片的量就相当可观;第二,也就是本文讲到的 xml 定义方式。

下面先上效果图:

正常时的文字颜色:



按下时的文字颜色:



以下为步骤:

先找到在values目录下的color.xml(定义的色彩xml,或为colors.xml,若没就创建)文件,在里面加入以下自定义颜色(注意不是用color标签)的代码:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--button中的文字变换色-->
<drawable name="button_text_white">#FFFFFF</drawable>
<drawable name="button_text_gray">#A4A4A4</drawable>

<!--dialog button 背景色-->
<color name="button_bg_black">#212121</color>
<color name="button_bg_gray">#7a7a7a</color>

</resources>


然后在res下新建drawable目录,里面新建selector_btn_click_bg.xml和sel_button_click_text_color.xml文件,代码如下:

sel_button_click_text_color.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:color="@drawable/button_text_gray" android:state_enabled="true"
android:state_focused="false"
android:state_pressed="false" />

<!--按下时的字体色  - 白色  -->
<item android:color="@drawable/button_text_white" android:state_pressed="true" />

<item android:color="@drawable/button_text_gray" android:state_focused="true" />

</selector>


selector_btn_click_bg.xm:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape android:bottomLeftRadius="4dp"
android:bottomRightRadius="0dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp">
<corners android:radius="0dp"/>
<gradient android:angle="90"
android:startColor="#acacac"
android:endColor="#acacac"/>
<stroke android:color="#acacac"
android:width="0dp"/>
</shape>

</item>

<!--正常色-->
<item>
<shape android:shape="rectangle">
<corners android:bottomLeftRadius="4dp"
android:bottomRightRadius="0dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp"/>
<gradient android:angle="90"
android:startColor="#cacaca"
android:endColor="#cacaca"/>
<stroke android:color="#cacaca"
android:width="0dp" />
</shape>
</item>
</selector>


最后,在布局的按钮上,添加statelist drawable修饰:

<!--...省略部分代码...-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:gravity="center_vertical">

<Button
android:id="@+id/bt_ed_dialog_off"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="@color/button_bg_gray"
android:text="取消"
android:textColor="@drawable/sel_button_click_text_color"
android:textSize="16sp" />

<!--android:background="@drawable/selector_btn_click_bg"
此处没有使用-->
<Button
android:id="@+id/bt_ed_dialog_ok"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="@color/button_bg_black"
android:text="确定"
android:textColor="@drawable/sel_button_click_text_color"
android:textSize="16sp" />

</LinearLayout>


OK,大功告成
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息