38

I'm using a very helpful example here to show a RecyclerView and a GridLayoutManager to show a grid with a header.

It looks pretty good, but my graphic designer wants the header item to take up the full width of the RecyclerView. Right now there is padding.

When I set up the GridLayoutManager I add in padding (which I still want for the other grid items): [it's using Xamarin C#]

var numColumns = myListView.MeasuredWidth / tileSizeMax;
myGridView.SetPadding(tilePadding, tilePadding, tilePadding, tilePadding);
layoutManager = new GridLayoutManager(Activity, numColumns);
myListView.SetLayoutManager(layoutManager);

So, how can I set the padding to be different for the header item...or make it draw itself over the padding?

Kibi
  • 1,860
  • 1
  • 29
  • 39

2 Answers2

101

Try with this:

mLayoutManager = new GridLayoutManager(this, 2);
        mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch(mAdapter.getItemViewType(position)){
                    case MyAdapter.HEADER:
                        return 2;

                    case MyAdapter.ITEM:
                    default:
                        return 1;
                }
            }
        });

And check these links:

Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
Alex
  • 6,957
  • 12
  • 42
  • 48
0

you can just do

val spanSize = 2
val mLayoutManager = GridLayoutManager(yourContext, spanSize)
mLayoutManager.spanSizeLookup = object : SpanSizeLookup() {
    override fun getSpanSize(position: Int): Int = when (position) {
        0 -> spanSize
        else -> 1
    }
}
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – dsadnick Apr 04 '22 at 14:21