Android. How to set different spacing between columns of a GridLayoutManager

174 views Asked by At

I need to set different spacing between the columns of the grid layout manager. To do this, I use the item decorator, but as a result I get the same distance, please tell me what might be wrong in my item decorator.

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

        int spaceHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4f, parent.getContext().getResources().getDisplayMetrics());
        int viewWidth = view.getLayoutParams().width;
        int centerSpace = parent.getWidth() - ((viewWidth * SPAN_COUNT) + (spaceHeight * 2));
        if (column == 1) {
            outRect.set(spaceHeight / 2, spaceHeight, centerSpace / 2, 0);
        } else if (column == 2) {
            outRect.set(centerSpace / 2, spaceHeight, spaceHeight / 2, 0);
        } else  {
            outRect.set(spaceHeight / 2, spaceHeight, spaceHeight / 2, 0);
        }

I have also tried setting margins inside my adapter, however this did not work as expected. The same margins are also obtained. Here is my code inside onBindViewHolder():

   int column = position % SPAN_COUNT;
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.rlParent.getLayoutParams();
            int centerSpace = recyclerView.getWidth() - ((layoutParams.width * SPAN_COUNT) + (mSpaceHeight * 2));
            if (column == 1) {
                layoutParams.setMargins(0, mSpaceHeight, centerSpace, 0);
            } else if (column != SPAN_COUNT - 1) {
                layoutParams.setMargins(0, mSpaceHeight, mSpaceHeight, 0);
            }
            holder.rlParent.setLayoutParams(layoutParams);

I need different distances between the columns in order to display the so-called seating chart of the aircraft seats. I found such a way to implement it, but it doesn't quite work for me.

https://github.com/TakeoffAndroid/SeatBookingRecyclerView

I need a solution that will work for a different number of columns.

For example, if the number of columns is four, then I need to increase the distance between the second and third columns. And if the number of columns is 6, then it is necessary to increase the distance between the second and third, and between 4 and 5 columns.

Here's an example of what I want to implement with 4 columns: example of expected result

0

There are 0 answers