问题描述
我有一个 RecyclerView
,其中行布局具有一些可点击的 TextView
元素,这些元素的背景设置为 ?attr/selectableItemBackground
。
我面临的问题是当我们滚动 RecyclerView 时会触发背景涟漪选择器,而不管 touch-n-scroll 操作的位置。这是一个演示此问题的视频(-它是在模拟器上拍摄的,因此有点笨拙):https://imgur.com/9MInNgv-查看为 X Comments
和 X Views
我尝试过的事情:
- 尝试使用自定义选择器而不是使用
selectableItemBackground
,但行为保持不变。 - 目前使用最新的 RecyclerView 版本 (1.2.0),也尝试使用旧版本,但问题依旧。
我的问题:
- 为什么只有某些视图才会发生这种情况?布局中有更多可点击的视图(例如:上面链接中看到的
Like
和Comment
按钮),但它只发生在演示的 2 个视图中。 - 如何防止这种情况发生?关于我可以尝试解决什么问题的任何线索?
提前致谢!
编辑:仅为包含触发涟漪的视图的部分添加布局 XML。这包含在用于该行的其他布局中(我也尝试在布局中直接使用此代码而不使用“包含”,但这不会改变任何行为):
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="@id/id_separator">
<androidx.appcompat.widget.LinearLayoutCompat
android:id="@+id/id_likes"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingStart="@dimen/_20sdp"
android:gravity="start|center"
android:background="?attr/selectableItemBackground" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/id_comments"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:includeFontPadding="false"
android:singleLine="true"
android:textAllCaps="false"
android:textStyle="normal"
android:textSize="@dimen/_12ssp"
android:background="?attr/selectableItemBackground"
tools:text="12 Comments" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/id_views"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingEnd="@dimen/_20sdp"
android:drawablePadding="@dimen/_3sdp"
android:gravity="end|center"
android:includeFontPadding="false"
android:singleLine="true"
android:textAllCaps="false"
android:textStyle="normal"
android:textSize="@dimen/_12ssp"
android:background="?attr/selectableItemBackground"
tools:text="12 Views"
tools:visibility="visible" />
</androidx.appcompat.widget.LinearLayoutCompat>
<View
android:id="@+id/id_separator"
android:layout_width="0dp"
android:layout_height="@dimen/_1sdp"
android:background="#1F000000"
android:layout_marginTop="@dimen/_30sdp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
解决方法
更新:我能够解决这个问题 - 只是将答案留在这里给遇到类似问题的任何人。
问题是出现此问题的 2 个视图的点击侦听器已从代码中注释掉,因为这些特定操作已推迟到未来版本。在当前版本中,我们只希望操作的行为就像单击父级一样。因此,我们只是简单地评论了他们的侦听器,以便父级处理点击事件。
为了使视图仍然可点击,我们仍然保留了 'selectableItemBackground' 属性,每当回收器视图项获得触摸事件时就会触发该属性。 只需添加一个点击监听器并调用 parent.performClick() 即可解决问题。