强制RecyclerView调用onCreateViewHolder [英] Force RecyclerView to call onCreateViewHolder

查看:1891
本文介绍了强制RecyclerView调用onCreateViewHolder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RecyclerView,可以将项目显示为列表,小网格或大网格,并且可以在运行时进行更改.根据用户选择的样式,我在onCreateViewHolder中填充不同的布局.

我还使用layoutManger.setSpanSizeLookUp()在样式之间进行切换.我的代码看起来像这样

I have a RecyclerView that can show items as list, small grids or large grid and this can be change at runtime. Depending on what style user chooses i inflate different layout in onCreateViewHolder.

I also use layoutManger.setSpanSizeLookUp() to switch between styles. My code looks like this

layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if(showType == ProductAdapter.SHOW_TYPE_SMALL_GRID)
                return 1;
            else
                return columnCount; //show one item per row
        }
    });

@Override
public void onClick(View v) {
    if(showType == ProductAdapter.SHOW_TYPE_SMALL_GRID)
        showType = ProductAdapter.SHOW_TYPE_LARGE_GRID;
    else
        showType = ProductAdapter.SHOW_TYPE_SMALL_GRID;


    int firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
    adapter = new ProductAdapter(getActivity(), productList, showType);
    recyclerView.setAdapter(adapter);
    layoutManager.scrollToPosition(firstVisibleItem);
}

问题是每次用户更改样式时都要强制调用onCreateViewHolder我正在创建一个新对象.还有其他办法吗?强制onBindViewHolder()被召回.我只是使用adapter.notifyDataSetChanged()我怎么能为onCreateViewHolder?得到类似的东西

任何不使用多个适配器的解决方案就足够了!

The problem is to force onCreateViewHolder to be called I'm creating a new object every time user changes the style. Is there any other way?! to force onBindViewHolder() to be recalled. I simply use adapter.notifyDataSetChanged() How can i get something similar for onCreateViewHolder?

Any solution that doesn't uses multiple adapters is good enough!

推荐答案

您需要做的是:

  1. 修改您的Adapter:

  • 指定Adapter可以充气的两种Views类型:
  • Specify two types of Views that your Adapter can inflate:

private static final int LARGE_GRID_ITEM = -1;
private static final int SMALL_GRID_ITEM = -2;

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆