Android Recycler并排查看项目

Android Recyclerview item side by side

我有回收站视图,里面有项目,可以垂直滚动。目前我实现的是像列表一样一个接一个地添加项目。我需要将它们并排放置。

喜欢下图

而我的输出是

我的回收站视图设置代码:

topicAdapter = new TopicAdapter(topicList, getActivity());
        topicListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        topicListView.setAdapter(topicAdapter);

适配器代码为:

public class TopicAdapter extends RecyclerView.Adapter<TopicAdapter.CategoryViewHolder> {
    private List<Topic> topicList;
    Context context;

    public TopicAdapter(List<Topic> topicList, Context context) {
        this.topicList = topicList;
        this.context = context;
    }

    @Override
    public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //inflate the layout file
        View groceryProductView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_suggested_topics, parent, false);
        CategoryViewHolder holder = new CategoryViewHolder(groceryProductView);
        return holder;
    }

    @Override
    public void onBindViewHolder(CategoryViewHolder holder, final int position) {
        holder.txtview.setText(topicList.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return topicList.size();
    }

    public class CategoryViewHolder extends RecyclerView.ViewHolder {
        TextView txtview;

        public CategoryViewHolder(View view) {
            super(view);
            txtview = view.findViewById(R.id.titleView);
        }
    }
}

添加这个

  topicListView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL,false));

我认为一个好的方法是使用 Material Choice Chips, you can learn how to use them here. You can then use a ChipGroup 将它们分组并允许它们跨多行流动。

但是,要解决您手头的问题,您可以使用 GridLayoutManager and then supply a SpanSizeLookup

您可以使用 Google 的最新设计组件 ChipGroup
否则,您可以通过在网格布局中显示标签来使用 Flexbox-Layout

如果您想使用 Flexbox-Layout,请选中

我可以建议您使用一个简单的解决方案,但是您无法使用此代码实现完整的要求。你们会并肩的。

替换

topicListView.setLayoutManager(new LinearLayoutManager(getActivity()));

topicListView.setLayoutManager(new GridLayoutManager(getActivity(), 3)); 

// 3 denotes the number of rows per column

将 StaggeredGridLayoutManager 用于 recyclerview