LayoutManager for RecyclerView Grid with different cell width

后端 未结 3 1647
半阙折子戏
半阙折子戏 2020-12-04 07:34

StaggeredGridLayoutManager doesn\'t seem to allow customising a cell width or span multiple columns (except full span) for vertical orientation

3条回答
  •  孤街浪徒
    2020-12-04 08:29

    For everyone else, looking for a solution without simplifying your layout, you can have a look to my answer here, or you can read more.

    Big thanks to Nick Butcher! His layout manager called SpannableGridLayoutManager is capable of doing this.

    1. Download SpannableGridLayoutManager from here

      For some reason I had to change this line:

      while (availableSpace > 0 && lastVisiblePosition < lastItemPosition) {
      

      to

      while (lastVisiblePosition < lastItemPosition) {
      

      to got the manager working.

    2. Set SpannableGridLayoutManger to your RecyclerView

    In your case:

    SpannedGridLayoutManager manager = new SpannedGridLayoutManager(
                new SpannedGridLayoutManager.GridSpanLookup() {
                    @Override
                    public SpannedGridLayoutManager.SpanInfo getSpanInfo(int position) {
                        switch (position % 8) {
                            case 0:
                            case 5:
                                return new SpannedGridLayoutManager.SpanInfo(2, 2);
    
                            case 3:
                            case 7:
                                return new SpannedGridLayoutManager.SpanInfo(3, 2);
    
                            default:
                                return new SpannedGridLayoutManager.SpanInfo(1, 1);
                        }
                    }
                },
                3, // number of columns
                1f // default size of item
        );
    

    Which will give you exactly what is in the first picture of the question.

提交回复
热议问题