以下是我的XML代码,我需要为LinearLayout制作一个选择器,但当我点击子TextView时,它不会将选择器背景显示为点击LinearLayout的其他区域!
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center_vertical"
android:clickable="true"
android:focusable="true"
android:descendantFocusability="blocksDescendants"
android:background="?android:attr/selectableItemBackground">
<ImageView android:paddingLeft="35dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/chart"/>
<TextView android:paddingLeft="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/tv_title" />
<ImageView android:paddingRight="15dp"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/ic_star_border_black_48dp"
android:id="@+id/iv_bookmark" />
</LinearLayout>
试试这个:
<TextView android:paddingLeft="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/tv_title"
android:clickable="false"
android:focusable="false" />
我认为错误的原因是descendantFocusability
仅用于聚焦状态。它不影响触摸事件。由于TextView
仍然是可点击的,它仍然可以消耗触摸事件,从而防止父对象消耗点击。
编辑:
尝试将android:descendantFocusability
设置为beforeDescendants
,而不是blocksDescendants
。
编辑2:
将父级更改为android:addStatesFromChildren="true"
,并从子级TextView
中删除clickable
和focusable
似乎起到了作用。这是因为根据ViewGroup
android文档:
addStatesFromChildren:设置此ViewGroup的可绘制状态是否也包括其子级的可绘制的状态。
因此,当孩子设定自己的状态时,也会设定父母的状态。
尝试在TextView
中将android:focusable
和android:focusableInTouchMode
设置为false
。