4

I want to switch the recyclerview with Grid and List Views.

But both the views should have different layout designs.

If LayoutManager is set and notified the switching works.

But how to update the UI based on the LayoutManager of the Recyclerview without recreating the adapter.

if(isListView){
                item.setIcon(getActivity().getResources().getDrawable(R.drawable.ic_list_view));
                GridLayoutManager lm = new GridLayoutManager(getActivity(),2);
                lm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        if (channelDetailAdapter != null) {
                            switch (channelDetailAdapter.getItemViewType(position)) {
                                case 0:
                                    return 2; //number of columns of the grid
                                default:
                                    return 1;
                            }
                        } else {
                            return -1;
                        }
                    }
                });
                rvChannelDetail.setLayoutManager(lm);
                isListView = false;
            }else{
                item.setIcon(getActivity().getResources().getDrawable(R.drawable.ic_grid_view));
                LinearLayoutManager lm = new LinearLayoutManager(getActivity());
                rvChannelDetail.setLayoutManager(lm);
                isListView = true;
            }
            channelDetailAdapter.notifyDataSetChanged();

If I notify the adapter the switch of LayoutManager works fine but if I add some layout change it is not reflecting.

Code inside adapter is

if(layout_type.getLayoutManager() instanceof GridLayoutManager){
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.content_media_grid_items, null);
            Media_Grid_ImageHolder viewHolder = new Media_Grid_ImageHolder(view);
            return viewHolder;
        }else{
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.content_media_list_items, null);
            Media_List_ImageHolder viewHolder = new Media_List_ImageHolder(view);
            return viewHolder;
        }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mathi Vanan
  • 101
  • 1
  • 9

1 Answers1

4

I think you must handle this problem in your view holder class.

return YourHolder(your view,viewType);

write only one view holder:

public class YourHolder extends RecyclerView.ViewHolder
{
 ...

public YourHolder(View itemView,int type)
{
    super(itemView);
    if(type==GRID_VIEW){
    // grid view initial
    }  if(type==LIST_VIEW){
    // list view initial
}  

I hope this work for you :)