Android RecyclerView: Change layout file LIST to GRID onOptionItemSelected

后端 未结 5 942
挽巷
挽巷 2020-12-02 06:34

I am developing an Android Application for Online Shopping. I have created following view for List of Products using RecyclerView, in that i want to change view

5条回答
  •  生来不讨喜
    2020-12-02 06:58

    I found solution with the starting of activity I have set LinearLayoutManager like:

    mLayoutManager = new LinearLayoutManager(this);
    mProductListRecyclerView.setLayoutManager(mLayoutManager);
    

    after that onOptionsItemSelected written like:

    case R.id.menu_product_change_view:
         isViewWithCatalog = !isViewWithCatalog;
         supportInvalidateOptionsMenu();
         //loading = false;
         mProductListRecyclerView.setLayoutManager(isViewWithCatalog ? new LinearLayoutManager(this) : new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
         mProductListRecyclerView.setAdapter(mAdapter);
         break;
    

    and changing view in onCreateViewHolder like:

    @Override
    public ProductRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(isViewWithCatalog ? R.layout.product_row_layout_list : R.layout.product_row_layout_grid, null);
        ProductRowHolder mh = new ProductRowHolder(v);
        return mh;
    }
    

    From Starting to Ending you have to manage isViewWithCatalog variable for displaying which layout first.

提交回复
热议问题