Android TextView的点击效果之改变背景颜色

在学习Android过程中,我们有时想要TextView有点击效果,不是文字的变化而是背景颜色的变化,那么怎么来实现呢?

下面将介绍如何实现:

1.在res目录下的drawable(此文件是自己手动创建的)文件下创建一个点击效果的文件:tv_bg_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#11000000"/>
        </shape>
    </item>
     <item android:state_pressed="false">
        <shape android:shape="rectangle">
            <!-- 透明色 -->
            <solid android:color="#00000000"/>
        </shape>
    </item>

</selector>

2.在布局控件中使用

    <TextView
        android:padding="5dp"
        android:clickable="true"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40sp"
        android:background="@drawable/tv_bg_selector"
        android:text="登录" />

接下来上效果图:

             

                  点击前                                                         点击后

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用 `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 时,背景颜色会从蓝色变为红色,松开时又会变回蓝色。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值