如何将RecyclerView LayoutManager从列表更改为网格?

问题描述 投票:1回答:1

我正在使用ViewPager,但我有一个RecyclerView,在这个RecyclerView中,我想将LayoutManager从List更改为Grid。

我已实现此代码:

    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);

在RecyclerView的onCreateViewHolder上,我有以下代码:

@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; 
}

我通过FloatingButton从List更改为Grid,更改了“ managerL”的值(这是一个布尔变量),因此,当我按下该按钮时,布局也会更改(从R.layout.item_list更改为R.layout_grid反之亦然),但布局管理器仍显示LinearLayoutManager。

我想知道,为什么我的RecyclerViewManager没有更改?

java android android-recyclerview gridlayoutmanager linearlayoutmanager
1个回答
0
投票

我认为您需要在每次单击后再次设置LayoutManagerAdapter

private LinearLayoutManager lLManager;
private GridLayoutManager glManager;

@Override
public View onCreateView(...) {
    View view = ...

    lLManager = new LinearLayoutManager(viewPager.getContext());
    glManager = new GridLayoutManager(viewPager.getContext(), 2);
    if (mData.size() % 2 != 0) { ... }

    setupRecycler();
    view.findViewById(R.id.myFab).setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            setupRecycler();
        }
    });
}

private void setupRecycler() {
    recycler.setLayoutManager(managerL ? lLManager : glManager);
    recycler.setAdapter(sAdapter);
}
热门问题
推荐问题
最新问题