【问题标题】:Pressed state for RecyclerView ItemRecyclerView 项的按下状态
【发布时间】:2018-02-19 06:23:26
【问题描述】:

我使用水平回收视图作为自定义底部导航栏。我想为每个项目定义一个按下状态,以便它们的颜色可以改变。

我尝试这样做,但无法管理它

<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>

回收站视图:

 <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">

【问题讨论】:

  • 尝试为 listItem 提供按下状态的背景并删除 android:clickable="true" android:focusable="true" android:focusableInTouchMode="true"

标签: android android-recyclerview


【解决方案1】:

使用 RecyclerView,您无法像使用 ListView 那样为每个项目定义和设置单个选择器。它必须在查看器级别完成。

所以每个项目布局都必须有一个选择器设置为背景。

<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 完成这项工作?
  • 如果您为 FrameLayout 或根视图设置了单击侦听器,则不必单击两次。一次就够了
  • 我有一个名为“MenuClickListener”的接口,我在其中传递菜单项及其 ID,我在我的活动中实现它
  • 如果你使用 holder.itemView.setOnClickListener 之类的东西,也许你可以删除 android:clickable="true" 标签
【解决方案2】:

首先,您可以使用“BottomNavigationBar”,它是一个 android 小部件,以便更好地实现。 即使您想将 recyclerView 用于相同的实现,请在 RecyclerView 项中使用这些属性,而不是 recyclerView 本身。

android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"

【讨论】:

  • 你正在使用一些自定义适配器并在那里膨胀一些视图,将这些元素放在那个视图中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 1970-01-01
相关资源
最近更新 更多