【问题标题】:RecyclerView's GridLayoutManager - rows Overlap on shorter screensRecyclerView 的 GridLayoutManager - 行在较短的屏幕上重叠
【发布时间】:2017-04-11 06:10:10
【问题描述】:

我有一个 RecyclerView,它的元素需要显示在 4 列中。我通过 GridLayoutManager 执行此操作,如下所示:

    mActivityBinding.bwRv.setAdapter(mAdapter);
    GridLayoutManager gridLayoutManager = new GridLayoutManager(MysActivityTwo.this, 4);
    mActivityBinding.bwRv.setLayoutManager(gridLayoutManager);

我的个人物品布局如下图:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="@dimen/bw_items_width"
    android:layout_height="100dp"
    android:layout_alignEnd="@+id/bw_et_questions"
    android:layout_alignStart="@+id/bw_et_questions"
    android:layout_below="@+id/bw_et_questions"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"
    card_view:cardCornerRadius="2dp"
    app:optCardBackgroundColor="@color/dark_font"
    card_view:cardElevation="2dp">
</android.support.v7.widget.CardView>

所以它有固定的高度和宽度。

在正常大屏幕中正确显示,但在小屏幕中,列相互重叠。有什么办法可以指定通常在较大的屏幕中它应该拾取 4 列但在较小的屏幕中它应该以某种方式包装而不重叠?

【问题讨论】:

    标签: android android-recyclerview gridlayoutmanager


    【解决方案1】:

    您可以根据屏幕尺寸定义布局。参考link

    对于大屏幕,您可以在 res/layouts/layout-large 中定义布局,对于小屏幕,您可以在 res/layout 中定义。

    【讨论】:

    • 是的,我知道我可以使用诸如 xxxhdpi 或 xxhdpi 之类的文件夹来定义。但我想要一些自动的方式让 maxColumns 可见。也就是说,如果列重叠而不是恢复列数。
    • 您可以在定义 layoutManager 之前检查屏幕宽度并相应地定义列数。
    【解决方案2】:

    使用此代码来分隔 Gridview 的项目。为间距创建一个类

    import android.graphics.Rect;
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private int space;
    public SpacesItemDecoration(int space) {
        this.space = space;
    }
    
    @Override
    public void getItemOffsets(Rect outRect, View view,
                               RecyclerView parent, RecyclerView.State state) {
        outRect.left = space;
        outRect.right = space;
        outRect.bottom = space;
    
        // Add top margin only for the first item to avoid double space between items
        if (parent.getChildLayoutPosition(view) == 0) {
            outRect.top = space;
        } else {
            outRect.top = 0;
        }
    }}
    

    并将其设置在您的 RecyclerView 上。

     int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
        recyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
    

    放在dimens.xml上

    <dimen name="spacing">2dp</dimen>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 2021-12-11
      相关资源
      最近更新 更多