Pinterest like Grid in Android

前端 未结 3 916
臣服心动
臣服心动 2021-01-31 22:51

I want to build a grid like the one in Pinterest app on Android.

I started extending an AdapterView but I cannot make many things working

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 23:26

    We won’t be needing any external library for this as Android’s native RecyclerView makes implementing a Pinterest masonry layout simply by changing the RecyclerView’s Layout Manager

    mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
    RecyclerAdapter adapter = new RecyclerAdapter(this);
    mRecyclerView.setAdapter(adapter);
    

    Cool. it's Very easy ,but margin on my LinearLayout didn’t seem to work. So here’s a quick fix.

    SpacesItemDecoration decoration = new SpacesItemDecoration(16);
    mRecyclerView.addItemDecoration(decoration);
    

    SpacesItemDecoration class:

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

    Github link of example

提交回复
热议问题