改变RecyclerView网格布局列数网格、布局、RecyclerView

2023-09-06 03:08:55 作者:刚好遇见你

我试图根据显示屏大小来改变出现在回收站视图(网格布局)列数。不过,我无法找出实现它的正确方法。目前我使用的 treeViewObserver 来更改列根据屏幕尺寸的变化(方向时)的数量。因此,如果应用程序在纵向模式,列数(在电话上)打开它决定是一个,这看起来不错,但是当应用程序在横向模式下直接打开这个方法不起作用,其中网格中的一个streched出牌显示在屏幕上。

I am trying to change the number of columns that appear in the recycler view (grid layout) based on the display size. However I couldn't figure out a proper way of achieving it. At the moment I am using treeViewObserver to change the number of columns based the change in screen size (during orientation). So if the app opens in portrait mode, number of columns (on the phone) it decides to be one, which look good but this method doesn't work when the app directly opens in landscape mode where a single streched out card in the grid is displayed on the screen.

这里recList是RecyclerView和放大器; GLM用于RecyclerView GridLayoutManager

    viewWidth = recList.getMeasuredWidth();

    cardViewWidthZZ = recList.getChildAt(0).getMeasuredWidth();

    if (oldWidth == 0) {
        oldWidth = cardViewWidthZZ;
    }

    if (oldWidth <= 0)
        return;

    int newSpanCount = (int) Math.floor(viewWidth / (oldWidth / 1.3f));
    if (newSpanCount <= 0)
        newSpanCount = 1;
    glm.setSpanCount(newSpanCount);
    glm.requestLayout();

最好的问候

推荐答案

如果你提供一个固定的列宽,可以延长 RecyclerView 并设置跨度计数 onMeasure 相应:

If you provide a fixed column width, you can extend RecyclerView and set the span count in onMeasure accordingly:

public AutofitRecyclerView(Context context, AttributeSet attrs) {
  super(context, attrs);

  if (attrs != null) {
    // Read android:columnWidth from xml
    int[] attrsArray = {
        android.R.attr.columnWidth
    };
    TypedArray array = context.obtainStyledAttributes(attrs, attrsArray);
    columnWidth = array.getDimensionPixelSize(0, -1);
    array.recycle();
  }

  manager = new GridLayoutManager(getContext(), 1);
  setLayoutManager(manager);
}

protected void onMeasure(int widthSpec, int heightSpec) {
  super.onMeasure(widthSpec, heightSpec);
  if (columnWidth > 0) {
    int spanCount = Math.max(1, getMeasuredWidth() / columnWidth);
    manager.setSpanCount(spanCount);
  }
}

有关更多信息,请参见我的博客文章: http://blog.sqisland.com/2014/12/recyclerview-autofit-grid.html

See my blog post for more info: http://blog.sqisland.com/2014/12/recyclerview-autofit-grid.html