两列宽度相等的 Android Studio CardView

问题描述

我试图在卡片视图中每行(两列)显示两个元素。但是,它们不在卡片视图中居中。 click here to see how the cardview displays items

这里是xml中的代码

 <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#Ffdb78"
            android:layout_below="@+id/LinearLayoutCateg"
            android:layout_above="@+id/menu"
            android:id="@+id/currentCategoryRecyclerView"/>

我在 Main 活动中以编程方式创建了一个新的 GridLayoutManager,如下所示:

 recyclerView.setLayoutManager(new GridLayoutManager(CategoryListActivity.this,2));
        recyclerView.setAdapter(categoryRecycler);

cardview 位于具有 "android:gravity="center" 属性的相对布局中,如果这很重要的话。 我不确定我错过了什么。

解决方法

我和你有同样的问题,我找到了 RecyclerView SpacingRecyclerView.ItemDecoration 类。

public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {

private int mItemOffset;

public ItemOffsetDecoration(int itemOffset) {
    mItemOffset = itemOffset;
}

public ItemOffsetDecoration(@NonNull Context context,@DimenRes int itemOffsetId) {
    this(context.getResources().getDimensionPixelSize(itemOffsetId));
}

@Override
public void getItemOffsets(Rect outRect,View view,RecyclerView parent,RecyclerView.State state) {
    super.getItemOffsets(outRect,view,parent,state);
    outRect.set(mItemOffset,mItemOffset,mItemOffset);
}

}

ItemOffsetDecoration 添加到您的 RecyclerView。
项目 offset 值应该是您要在项目之间添加空格的实际值的一半。

 mRecyclerView.setLayoutManager(new GridLayoutManager(context,NUM_COLUMNS);
ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(context,R.dimen.item_offset);
mRecyclerView.addItemDecoration(itemDecoration);

此外,将 item offset 值设置为其 RecyclerView 的填充,并指定 android:clipToPadding=false

<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:padding="@dimen/item_offset"/>    <!--Give a desired size-->

refer

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...