您的位置:首页 > 其它

使用selector改变文字的颜色

2015-07-30 14:25 435 查看
有时候为了提高用户体验,我们希望有些文字按下去的时候改变颜色,这时候就要用到selector了。代码如下。

首先在drawable文件夹下定义一个selector文件:如下(我的应用场景是 相对布局中有一行文字,点击相对布局文字颜色改变,state选的是pressed )

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- drawable -->
<item android:state_pressed="false" android:drawable="@color/bg_gray6"/>
<item android:state_pressed="true" android:drawable="@color/e1e1e1"/>
</selector>

刚开始也以为定义好这个文件后,在布局文件中的Textview中直接引用就可以,但是没有效果,后来才知道还需要再加两行其他的代码,如下:(很关键,加上后想要的就出现了,在父控件中添加android:clickable=“true” android:focusable=“true”,而在子控件中添加android:duplicateParentState=“true”子控件就能获得父控件的点击事件)

<RelativeLayout
android:id="@+id/rl_cleancache"
android:layout_width="fill_parent"
android:layout_height="38dp"
android:clickable="true"
android:focusable="true"
android:background="@drawable/my_bg_selector"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:duplicateParentState="true"
android:layout_marginLeft="10dp"
android:textColor="@color/setting_color_selector"
android:textSize="@dimen/font_size_normal"
android:text="清除缓存"
/>

</RelativeLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: