Android Recyclerview : change row from linear to grid on button click

2.1k Views Asked by At

On button click I want to change list view to gridview as on shopping-cart pages but my layout looks like link shown below.

//For displaying the row as linear list view        
case R.id.ivGrid:
    ivList.setVisibility(View.VISIBLE);
    ivGrid.setVisibility(View.GONE);
    LinearLayoutManager llm = new LinearLayoutManager(context);
    rcvProducts.setLayoutManager(llm);
    break;

//For displaying the row as gridview
case R.id.ivList:
    ivList.setVisibility(View.GONE);
    ivGrid.setVisibility(View.VISIBLE);
    GridLayoutManager glm = new GridLayoutManager(this,2,GridLayoutManager.VERTICAL, false);
    rcvProducts.setLayoutManager(glm);
    break;

GRIDview

LISTview

2

There are 2 best solutions below

0
On

Just use a GridLayoutManager and change the span count from 1 to 2 and back again.

view.setOnClickListener(new View.OnClickListener(){
    public void onClick(View view){
        GridLayoutManager layoutManager = (GridLayoutManager) grid.getLayoutManger();
        layoutMananger.setSpanCount(layoutManager.getSpanCount() == 2 ? 1 : 2);
    }
})
2
On
  1. Maintain 2 adapters, one for ListView and one for GridView.
  2. On button click, change the adapter to RecyclerView.
  3. Listview.setAdapter(gridAdapter) (or) ListView.setAdapter(listAdapter)