Android如何让TextView子元素随着父元素的背景变化而改变字体颜色?

Android如何让TextView子元素随着父元素的背景变化而改变字体颜色?


重点在于

android:duplicateParentState="true"

首先创建两个XML:

父元素背景选择器 item_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/black" android:state_pressed="true"></item>
    <item android:drawable="@color/yellow"></item>
</selector>

子元素颜色选择器 text_bg.xml

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


布局文件:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        <span style="color:#ff0000;">android:background="@drawable/item_bg"</span>
        android:clickable="true">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            <span style="color:#ff0000;">android:duplicateParentState="true"</span>
            android:gravity="center"
            android:text="测试"
            <span style="color:#ff0000;">android:textColor="@drawable/text_bg"</span>
            android:textSize="30dp" />
    </LinearLayout>
</RelativeLayout>


color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="yellow">#FF9800</color>
    <color name="black">#000000</color>
    <color name="white">#FFFFFF</color>
</resources>



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值