dynamic更改GridLayoutManager的列数

我实际上是在我的应用程序中使用两列的GridLayoutManager,我希望有一列取决于使用的视图types。

这里是我的片段的方法“onCreateView()”中的代码:

// Recycler view for users usersList = (RecyclerView) mView.findViewById(R.id.usersList); // Layout manager (grid of users layoutManager = new GridLayoutManager(mContext, 2); usersList.setLayoutManager(layoutManager); // ArrayList of users users = new ArrayList<User>(); // Set the adapter for the list of users mHomeListAdapter = new HomeListAdapter(getActivity(), users); usersList.setAdapter(mHomeListAdapter); 

然后,在我的适配器中,我有这样的代码:

 @Override public int getItemViewType(int position) { if (position == 5) { return TYPE_PREMIUM; } else { return TYPE_ITEM; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_PREMIUM) { View view = mInflater.inflate(R.layout.become_premium, parent, false); HeaderViewHolder holder = new HeaderViewHolder(view); return holder; } else { View view = mInflater.inflate(R.layout.posts_item, parent, false); ViewHolderPosts holder = new ViewHolderPosts(view); return holder; } } 

所以,当使用“TYPE_PREMIUM”视图时,我想显示一个button(所以在一列中),并有一个正常的网格视图(两列)的其他结果。

是否有可能做到这一点?

谢谢!

Solutions Collecting From Web of "dynamic更改GridLayoutManager的列数"

 mGridLayoutManager = new GridLayoutManager(mContext, 2); mGridLayoutManager.setSpanSizeLookup(onSpanSizeLookup); /** * Helper class to set span size for grid items based on orientation and device type */ GridLayoutManager.SpanSizeLookup onSpanSizeLookup = new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return mHomeListAdapter.getItemViewType(position) == TYPE_PREMIUM ? 2 : 1; } }; 

如果我理解你的问题,你想让高级types的视图跨2列而不是1? 这可以通过使用setSpanSizeLookup(SpanSizeLookup)设置一个自定义的SpanSizeLookup来实现 。