RecyclerView中的CardView没有点击效果。

3

我正在使用 RecyclerViewGridLayoutManager,并且我动态添加新元素,这些元素有以下 xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawSelectorOnTop="true">

    <android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground"
        style="@style/cardView">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center">

            <ImageView
                android:id="@+id/direction_list_icon"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:src="@drawable/icon"
                android:layout_gravity="center"
                android:padding="8dp"
                android:clickable="true" />

            <TextView
                android:id="@+id/direction_list_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Dummy text"
                android:layout_gravity="center"
                android:padding="8dp"
                android:clickable="true" />

        </LinearLayout>
    </android.support.v7.widget.CardView>  
</LinearLayout>

问题在于只有在我双击或长按时才能看到对 CardView 项的点击效果。
我尝试在 CardView 中放置一个 LinearLayout,并使用 android:background="?android:attr/selectableItemBackground" 使其可点击,但结果仍然相同。

1
只有将RecyclerView替换为GridView才能解决问题。 - snitsaruk
但是如果我想使用 RecyclerView 呢? - temirbek
2个回答

3

我在我的项目中通过将背景设置为CardView的根元素来解决了这个问题。在您的布局中,这应该可以工作:

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    style="@style/cardView">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        android:background="?android:selectableItemBackground">

    </LinearLayout>
</android.support.v7.widget.CardView>

0

设置

android:focusable="false"
android:focusableInTouchMode="false"

在你的CardView上


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