Warm tip: This article is reproduced from stackoverflow.com, please click
android

How to add dynamic number of cells in a horizontal recyclerview that spans to the complete width of

发布于 2020-03-27 10:30:00

I want to have a horizontal recyclerview or a similar view that can have dynamic no of items that would span to the entire width of the view and the view won't be scrollable. So , for example the horizontal recyclerview would have a width of match_parent and if we specify that it will have 4 items, then the entire width of the recyclerview will be divided equally between the 4 items and the same even if there were 10 items.

Questioner
Julie
Viewed
21
ph7 2019-07-04 01:22

One way is to divide display width by item count.

In your Adapter you have method, from there you get item count

    @Override
public int getItemCount() {
    return your_items.length;
}

and in onCreateViewHolder you can change width of your item layout

 @Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
    // create a new view
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_view, parent, false);

    //get device screen width
    int width  = Resources.getSystem().getDisplayMetrics().widthPixels;
    //set your item view width
    v.getLayoutParams().width = width / getItemCount() ;

    MyViewHolder vh = new MyViewHolder(v);
    return vh;
}

Not tested, but it should work.