您的位置:首页 > 其它

背景选择器selector替换按钮默认背景

2015-11-30 12:58 155 查看

一、效果

正常状态



获取焦点或按下



按钮的背景图片是.9图,.9图的制作过程,见下面博文

/article/10292577.html

二、步骤

模仿android自带的按钮控件编写
1、找到android自带按钮的样式。
D:\ADT\sdk\platforms\android-16\data\res\values\style.xml文件中找Button控件,
<item name="android:background">@android:drawable/btn_default</item>是背景选择器,不是图片。

代码如下。

<style name="Widget.Button">
<item name="android:background">@android:drawable/btn_default</item>
<item name="android:focusable">true</item>
<item name="android:clickable">true</item>
<item name="android:textAppearance">?android:attr/textAppearanceSmallInverse</item>
<item name="android:textColor">@android:color/primary_text_light</item>
<item name="android:gravity">center_vertical|center_horizontal</item>
</style>
2、查找Button的背景选择器代码。
找到D:\ADT\sdk\platforms\android-16\data\res\drawable\btn_default.xml
代码如下:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:state_enabled="true"
android:drawable="@drawable/btn_default_normal" />
<item android:state_window_focused="false" android:state_enabled="false"
android:drawable="@drawable/btn_default_normal_disable" />
<item android:state_pressed="true"
android:drawable="@drawable/btn_default_pressed" />
<item android:state_focused="true" android:state_enabled="true"
android:drawable="@drawable/btn_default_selected" />
<item android:state_enabled="true"
android:drawable="@drawable/btn_default_normal" />
<item android:state_focused="true"
android:drawable="@drawable/btn_default_normal_disable_focused" />
<item
android:drawable="@drawable/btn_default_normal_disable" />
</selector>


3、模仿着写。先写样式,再写选择器。
样式NextStyle代码如下:
<style name="NextStyle">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_alignParentBottom">true</item>
<item name="android:layout_alignParentRight">true</item>
<item name="android:background">@drawable/btn_green_selector</item>
<item name="android:drawableRight">@drawable/next</item>
<item name="android:text">下一步</item>
<item name="android:onClick">next</item>
</style>
选择器btn_green_selector.xml的代码如下:一个选择器一个xml文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 按下 -->
<item android:drawable="@drawable/btn_green_pressed" android:state_pressed="true"/>
<!-- 获取焦点 -->
<item android:drawable="@drawable/btn_green_pressed" android:state_focused="true"/>
<!-- 默认,默认放在最后-->
<item android:drawable="@drawable/function_greenbutton_normal"/>
</selector>


4、布局文件中使用
代码如下
<Button style="@style/NextStyle" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: