Skip to content
Advertisement

How to change RecyclerView LayoutManager from List to Grid?

I’m using a ViewPager in which I have a RecyclerView, in this RecyclerView I want to change the LayoutManager from List to Grid.

I’ve implemented this code:

 void setLManager(boolean managerL){
    GridLayoutManager glManager = new GridLayoutManager(viewPager.getContext(), 2);
      if (mData.size() % 2 != 0) {
          final int item = mData.size() - 1;
          glManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
              @Override
              public int getSpanSize(int position) {
                  return position == item ? 2 : 1;
              }
          });
      }
    LinearLayoutManager lLManager = new LinearLayoutManager(viewPager.getContext());

    recycler.setLayoutManager(managerL ? lLManager : glManager);
    sAdapter.notifyDataSetChanged();
    recycler.setAdapter(sAdapter);
}

On the RecyclerView’s onCreateViewHolder I have the following code:

@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View v;

        int layout = 0;

        if(viewType == Util.LIST){

            layout = R.layout.item_list;

        }else {

            layout = R.layout.item_grid;

        }
        v = LayoutInflater.from(mContext).inflate(layout, parent, false);
        viewHolder = new RecyclerView.ViewHolder(v);
        return viewHolder; 
}

I make the change from List to Grid through a FloatingButton, changing the value of “managerL” (this is a boolean variable) so, when I press the button, the layouts change (from R.layout.item_list to R.layout_grid and vice versa), but the layout manager still showing the LinearLayoutManager.

I’d like to know, why isn’t my RecyclerViewManager changing?

Advertisement

Answer

I found what was the problem I had in my code and with this, I found a solution, the problem was in the adapter of my ViewPager, and I found the solution in this answer: https://stackoverflow.com/a/18710611

The reason why my RecyclerView didn’t change from LayoutManager, was that in my ViewPager adapter it showed the RecyclerView layout with a LayoutInflater, and for some reason this made my RecyclerView not make the change from list to grid, in the link I left above, there is a better way to create the adapter for the ViewPager and it was the one that worked for me.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement