如何在交错网格布局管理器中确定列位置 [英] How to determine column position in staggered grid layout manager

查看:151
本文介绍了如何在交错网格布局管理器中确定列位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用交错的回收站视图布局来显示照片列表.我希望两侧的间距为零,而两列之间仍要有间距.我使用的是商品装饰子类,以获取所附照片中的间距.我知道我可以控制左右间距,但是问题是我永远不知道照片在哪一列中.似乎交错的布局管理器会自己进行一些重新排序.我尝试使用getChildAdapterPosition,但它似乎返回数据源数组中的位置,而不是布局中照片的实际位置.知道我该如何处理吗?

I’m using a staggered recycler view layout for a list of photos. I want the spacing on the sides to be zero while still having space between the two columns. I’m using an item decoration sub class to get the spacing seen in the attached photo. I know I have control over the left and right spacing but the problem is that I never know which column the photo is in. It seems like the staggered layout manager does some of its own reordering. I've tried using getChildAdapterPosition but it seems to return the position in the data source array and not the actual position of the photo in the layout. Any idea how I should approach this?

推荐答案

我设法使其正常运行.就我而言,在屏幕的左边缘或右边缘不需要任何边框.我只需要中间和底部有边界即可.解决方案是获取类型为StaggeredGridLayoutManager.LayoutParams的视图的布局参数.在这些参数中,您可以获取spanIndex,该值可以告诉您视图位于哪个索引上.因此,如果spanCount为2,则左视图的spanIndex为0,右视图的spanIndex为1.

I managed to get it working. In my case, I don't need any borders on the left or right edges of the screen. I just need borders in the middle and bottom. The solution is to get the layout parameters of the view that are of type StaggeredGridLayoutManager.LayoutParams. In those parameters you can get the spanIndex that tells you on which index the view is. So if you have a spanCount of 2, the left view will have a spanIndex of 0 and the right view will have a spanIndex of 1.

这是我的代码,也许对您有帮助.

Here is my code, maybe it help you.

public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
private int space;

public SpaceItemDecoration(int space) {
    this.space = space;
}


@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    int position = parent.getChildAdapterPosition(view);

    StaggeredGridLayoutManager.LayoutParams lp = (StaggeredGridLayoutManager.LayoutParams)view .getLayoutParams();
    int spanIndex = lp.getSpanIndex();

    if(position > 0){
        if(spanIndex == 1){
            outRect.left = space;
        } else{
            outRect.right = space;
        }

        outRect.bottom = space * 2;
    }
}

}

在我的情况下,首先,我必须获得位置,因为在索引0上,我有一个标题视图,该标题没有任何边框.之后,我获得了跨度索引,并根据该索引设置了该视图上所需的边界.最后,我在每个视图上设置底部边框.

In my case, firstly I have to get the position, since on the index 0 I have a header View, which doesn't have any borders. After that, I get the span index and depending on it I set the borders that I need on that View. And finally I set the bottom border on every View.

这篇关于如何在交错网格布局管理器中确定列位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆