TextView 点击、获得焦点等 改变颜色

有的时候我们需要根据文字是否获取焦点而改变颜色。

做法如下:

在res目录下新建color文件夹,在文件夹下新建xxx.xml文件。

文件内容如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/text_black" android:state_pressed="true" />
    <item android:color="@color/text_black" android:state_focused="true" />
    <item android:color="@color/text_black" android:state_selected="true" />
    <item android:color="@color/text_black" android:state_activated="true" />
    <item android:color="@color/text_gray_b0" />
</selector>

然后引用的时候:

android:textColor="@color/xxx"
就可以了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 `StateListDrawable` 来实现在 TextView改变背景的样式。下面是一个示例: 1. 首先,在 `res/drawable` 目录下创建一个名为 `background_selector.xml` 的文件,用于定义 `StateListDrawable`: ```xml <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/pressed_background" /> <item android:drawable="@drawable/normal_background" /> </selector> ``` 上面的代码定义了两个状态:`state_pressed` 表示按下时的状态,`drawable` 表示对应的背景。当 TextView 被按下时,会显示 `pressed_background` 背景;否则,显示 `normal_background` 背景。 2. 接着,在 `res/drawable` 目录下创建 `pressed_background.xml` 和 `normal_background.xml` 两个文件,分别表示按下和普通状态下的背景。这里以红色和蓝色为例: `pressed_background.xml`: ```xml <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#FF0000" /> </shape> ``` `normal_background.xml`: ```xml <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#0000FF" /> </shape> ``` 3. 最后,在布局文件中,将 TextView 的 background 属性设置为 `background_selector` 即可: ```xml <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:background="@drawable/background_selector" /> ``` 这样,当用户点 TextView 时,背景颜色会从蓝色变为红色,松开时又会变回蓝色。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值