android - 更改 RecyclerView 网格布局中的列数

标签 android gridlayoutmanager

我正在尝试根据显示大小更改回收站 View (网格布局)中显示的列数。但是我无法找到实现它的正确方法。目前,我正在使用 treeViewObserver 根据屏幕尺寸的变化(在方向期间)更改列数。因此,如果应用程序以纵向模式打开,则(在手机上)它决定为一列,这看起来不错,但是当应用程序直接以横向模式打开时,此方法不起作用,其中网格中有一张拉伸(stretch)的卡片显示在屏幕上。

这里的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();

最好的问候

最佳答案

public class VarColumnGridLayoutManager extends GridLayoutManager {

private int minItemWidth;

public VarColumnGridLayoutManager(Context context, int minItemWidth) {
    super(context, 1);
    this.minItemWidth = minItemWidth;
}

@Override
public void onLayoutChildren(RecyclerView.Recycler recycler,
        RecyclerView.State state) {
    updateSpanCount();
    super.onLayoutChildren(recycler, state);
}

private void updateSpanCount() {
    int spanCount = getWidth() / minItemWidth;
    if (spanCount < 1) {
        spanCount = 1;
    }
    this.setSpanCount(spanCount);
}}

关于android - 更改 RecyclerView 网格布局中的列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27744788/

相关文章:

android - Cocos2dx Android : getFileData failed to get . 来自 Assets 的json文件

Android - 如何禁用长按搜索按钮 (Nexus One)

java - android:installLocation ="preferExternal"和 WRITE_EXTERNAL_STORAGE 权限

java - 如何在 GridLayoutManager 中改变每条偶数行的方向?

android - Recyclerview 与 Gridlayoutmanager

android - RecyclerView 与 GridLayoutManager

android - 背景简历上的密码

android - ContentValues 将值作为 sql 条件

android - 回收器网格布局管理器中的行和列跨度

android - 在 RecyclerView 中绘制空单元格