RecyclerView项目的按下状态

6
我正在使用水平的RecyclerView作为自定义底部导航栏。我想为每个项目定义按下状态,以便它们的颜色可以改变。 我尝试这样做,但无法成功。
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/menu_pressed" android:state_activated="true" />
    <item android:drawable="@color/menu_pressed" android:state_pressed="true" />
    <item android:drawable="@color/menu_pressed" android:state_checked="true" />
    <item android:drawable="@color/menu_pressed" android:state_focused="true" />
    <item android:drawable="@color/menu" />
</selector>

RecyclerView:

 <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="65dp"
        android:layout_gravity="bottom"
        android:background="@drawable/menu_selector"
        android:fadingEdge="vertical|horizontal"
        android:fadingEdgeLength="60dp"
        android:fillViewport="false"
        android:requiresFadingEdge="horizontal|vertical"
        app:layoutManager="android.support.v7.widget.LinearLayoutManager"
        android:clickable="true"
        android:focusable="true"
        android:focusableInTouchMode="true">

1
尝试将“state_pressed”背景赋予listItem并删除以下属性: android:clickable="true" android:focusable="true" android:focusableInTouchMode="true" - Rahul
2个回答

4

使用RecyclerView时,无法像ListView一样为每个项目定义和设置单个选择器。必须在viewholder级别上完成。

因此,每个项目布局都必须设置选择器作为背景。

<FrameLayout
    android:id="@+id/frame"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:background="@drawable/menu_selector">

然后在你的适配器onBind中,你可以设置一个点击监听器,它应该会起作用。

holder.frame.setOnClickListener {
  // do something
}

这会在我点击时更改背景颜色,但我必须点击两次才能使onclicklistener完成工作? - Ege Kuzubasioglu
如果您将单击侦听器设置为FrameLayout或根视图,则不需要点击两次。一次就足够了。 - Eoin
我有一个名为 "MenuClickListener" 的接口,在其中传递菜单项和它们的 ID,我在我的活动中实现它。 - Ege Kuzubasioglu
如果您使用类似holder.itemView.setOnClickListener的东西,也许可以删除android:clickable="true"标记。 - Eoin

0
首先,您可以使用“BottomNavigationBar”,它是一种Android小部件,可用于更好的实现。即使您想要使用recyclerView进行相同的实现,也请在RecyclerView项目中使用这些属性,而不是recyclerView本身。
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"

你正在使用一些自定义适配器并在其中填充一些视图,请将这些元素放入该视图中。 - KKSINGLA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接