3

I have recycler-view with items in it and can be scrolled vertically. Currently what i achieved is items are added one after another like a list. By i need to place them side by side.

Like the image below

Target

And my output is

Output

My recycler-view setup code:

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

and adapter code is:

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);
        }
    }
}
Ahsan Aasim
  • 957
  • 2
  • 8
  • 33

5 Answers5

1

I can suggest you with a simple solution but, you cant achieve complete requirement with this code. You'll get side by side.

Replace

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

with

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

// 3 denotes the number of rows per column
tuomastik
  • 4,122
  • 5
  • 33
  • 44
Chethan Kumar
  • 175
  • 1
  • 12
0

Add This

  topicListView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL,false));
mehul chauhan
  • 1,737
  • 10
  • 25
0

I think a good way to do this is by using Material Choice Chips, you can learn how to use them here. You can then use a ChipGroup to group them and allow them to flow across multiple lines.

However, to solve your question at hand, you can use a GridLayoutManager and then supply a SpanSizeLookup.

Anthony Cannon
  • 1,192
  • 8
  • 20
0

You can do this using Google's latest design component ChipGroup
Else you can use Flexbox-Layout by showing your tags in Grid Layout.

If you wish to go for Flexbox-Layout, check answer of avik

Varad Mondkar
  • 1,351
  • 1
  • 16
  • 28
0

Use StaggeredGridLayoutManager for recyclerview

Parth Suthar
  • 123
  • 4