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>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="yellow">#FF9800</color>
<color name="black">#000000</color>
<color name="white">#FFFFFF</color>
</resources>
![](https://i-blog.csdnimg.cn/blog_migrate/a52e33ff7fe542b05d21d06c3b482601.png)