如何动态更改为 GridLayoutManager 列

How to change to GridLayoutManager column dynamically

我有一个附有 GridLayoutManager 的 Recycler 视图。默认情况下,它将显示一列,如果用户单击按钮,它将显示在两列中。

adapter = new ProductAdapter(getActivity(), productList);
        gridLayoutManager = new GridLayoutManager(getActivity(), 1);
        setLayoutManager(true);

下面是我正在更改列的函数

  private void setLayoutManager(boolean isList) {
        if (isList) {
            adapter.VIEW_TYPE = 0 ;
            gridLayoutManager.setSpanCount(1);
            //product_recycler_view.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
            product_recycler_view.setLayoutManager(gridLayoutManager);

        } else {
            adapter.VIEW_TYPE = 1 ;
            gridLayoutManager.setSpanCount(2);
            product_recycler_view.setLayoutManager(gridLayoutManager);
        }
        product_recycler_view.setAdapter(adapter);
        adapter.notifyDataSetChanged();
       // product_recycler_view.notify();
       // product_recycler_view.notifyAll();

        System.out.println("clicked isList "+ isList);

    }

试试这个

  private void setLayoutManager(boolean isList) {
        if (isList) {
           product_recycler_view.setLayoutManager(new LinearLayoutManager(this));
        } else {
           product_recycler_view.setLayoutManager(gridLayoutManager);
        }
        product_recycler_view.setAdapter(adapter);
        adapter.notifyDataSetChanged();
       // product_recycler_view.notify();
       // product_recycler_view.notifyAll();

        System.out.println("clicked isList "+ isList);
}