【问题标题】:Android Studio CardView with two columns that have equal widthAndroid Studio CardView 有两列宽度相等
【发布时间】:2021-09-20 13:29:58
【问题描述】:

我试图在卡片视图中显示每行(两列)的两个元素。但是,它们不在卡片视图中居中。 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 Activity 中以编程方式创建了一个新的 GridLayoutManager,如下所示:

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

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

【问题讨论】:

  • 提供您的 cardview xml。可能需要更改android:layoutWidthandroid:layoutHeight 属性。
  • 感谢您的建议。但是,Ganesh 的解决方案非常有效!

标签: java android android-studio multiple-columns cardview


【解决方案1】:

我和你有同样的问题,我找到了 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, mItemOffset);
}

}

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

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

另外,将项目 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

【讨论】:

  • 非常适合我!谢谢!
猜你喜欢
  • 2013-04-27
  • 1970-01-01
  • 2020-11-30
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
相关资源
最近更新 更多