在下面的内容中,尽管文本在单击布局时更改了颜色,但是尽管我在代码中明确设置了view.setSelected(true)
,但颜色并没有持久:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="40dp"
android:gravity="center"
android:orientation="horizontal"
android:clickable="true"
android:focusable="true"
>
<TextView
android:id="@+id/txt"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingStart="16dp"
android:gravity="center_vertical"
android:text="Test String"
android:background="@drawable/background_disabled"
android:textColor="@color/selector_selection"/>
/>
</LinearLayout>
// background_disabled.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/red"/>
</shape>
</item>
<item android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="@color/white"/>
</shape>
</item>
</layer-list>
// selector_selection.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/green" android:state_pressed="false"/>
<item android:color="@color/red" android:state_pressed="true"/>
<item android:color="@color/red" android:state_selected="true"/>
</selector>
在单击LinearLayout
时,文本的颜色确实发生了变化,但是即使我将setSelected(true)
设置为父版面,它也会切换回禁用的颜色。
我怎样才能解决这个问题?
更新:
通过按如下所示更改选择器,它可以工作:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/red" android:state_pressed="true"/>
<item android:color="@color/red" android:state_selected="true"/>
<item android:color="@color/green"/>
</selector>
基本上,我删除了false
状态并在最后添加了默认值。
为什么这可以解决问题?