首页 > 解决方案 > 为每个 GridLayout 正方形添加分隔线和波纹效果

问题描述

我正在使用 RecyclerView + GridLayout(3 列)。现在,为了让网格的每个方格更“响应”,我希望每个方格都显示某种分隔线,并且用户点击的每个方格内都会产生涟漪效应。

编辑:我添加了android:foreground="?attr/selectableItemBackground",但没有任何反应。这是现在的单项 xml 代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="6dip" >

    <ImageView
        android:foreground="?attr/selectableItemBackground"
        android:id="@+id/icon"
        android:layout_width="128dp"
        android:layout_height="118dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="12dp"
        android:layout_marginEnd="12dp"
        android:layout_marginTop="12dp"
        android:contentDescription="TODO"
        android:src="@drawable/ic_launcher_background" />
</RelativeLayout>

这是它目前的样子: NoRippleDivider

这就是我希望它看起来的样子: 在此处输入图像描述

这是修复后当前的工作方式,添加后:

android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"

在此处输入图像描述

标签: androidandroid-recyclerviewrippledrawable

解决方案


如果您希望对其进行自定义,您可以像这样创建一个可绘制的波纹:

波纹.xml

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorPrimaryDark">
<item android:id="@android:id/mask">
    <shape android:shape="rectangle">
        <solid android:color="@color/colorPrimaryLight" />
        <!--<corners android:radius="@dimen/button_radius_large" />-->
    </shape>
</item>

<item android:id="@android:id/background">
    <shape android:shape="rectangle">
        <gradient
            android:angle="90"
            android:endColor="@color/background"
            android:startColor="@color/background"
            android:type="linear" />
        <!--<corners android:radius="10dp" />-->
    </shape>
</item>

并在您的布局中使用它,如下所示:

android:clickable="true"
android:background="@drawable/ripple"

或者你可以简单地这样做:

android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"

推荐阅读