Android初级教程:如何自定义一个状态选择器

来源:互联网 发布:matlab7,1如何进入编程 编辑:程序博客网 时间:2024/05/22 14:36

有这样一种场景:点击一下某个按钮或者图片(view),改变了样式(一般改变背景颜色)。这个时候一种解决方案,可能就是状态选择器。接下来就介绍如何实现状态选择器:

步骤:

一、新建这样的文件夹:res/drawable

二、创建一个xml文件;这里命名为my_select.xml(注意选择select类型的文件)

三、接下来在里面写如下代码:

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" >         <item android:state_pressed="true"          android:drawable="@drawable/btn_green_pressed" /> <!-- pressed按下的颜色背景图片。也可以在values目录下新建color文件引入颜色 -->        <item android:state_pressed="false"        android:drawable="@drawable/btn_green_normal" /> <!-- default默认的背景图片 --></selector>

注意:那两个引用的图片是自己随便放的,自己喜欢改变即可。

四、在布局文件给button按钮设置成这个选择器,代码如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <Button        android:layout_centerInParent="true"        android:background="@drawable/bt_select"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="点我改变颜色哦" /></RelativeLayout>

现在运行程序就行了,看效果图:

可以看到,默认是自己设置的绿色图片背景,按下成了棕黄色背景。

如果设置颜色选择器,效果如下:


但是个人建议不要使用颜色作为选择器,对于内部原因,现在的知识还无法解释。因为有些view加入颜色选择器会出问题,希望以后能明白具体原理吧。懂得前辈,也可以留言解释一下,提前感谢O(∩_∩)O


1 0
原创粉丝点击