我实际上在我的应用程序中使用了一个带有两列的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(); // 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”时,我想显示一个按钮(在一列中),并为其他结果显示正常的gridview(两列)。
是否有可能做到这一点?
谢谢!
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来实现 。