match_parent width does not work in RecyclerView

try this when you set layout params for your item in adapter.

 View viewHolder= LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item, parent, false);
 viewHolder.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
 ViewOffersHolder viewOffersHolder = new ViewOffersHolder(viewHolder);
 return viewOffersHolder;

I was using a FrameLayout with MATCH_PARENT for width and was seeing the same behavior with a RecyclerView + LinearLayoutManager. None of the above changes worked for me until I did the following in the onCreateViewHolder callback:

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // create a new view
    View v = LayoutInflater.from(parent.getContext())
                           .inflate(R.layout.note_layout, parent, false);
    v.setLayoutParams(new RecyclerView.LayoutParams(
          ((RecyclerView) parent).getLayoutManager().getWidth(),
          context.getResources()
                 .getDimensionPixelSize(R.dimen.note_item_height)));

    return new ViewHolder(v);
}

Clearly looks like a bug in (I'm guessing) the RecyclerView implementation.


Inside onCreateViewHolder(...) method of adapter where you are inflating the view.. you have to define the ViewGroup as the parent.This you will get from the 1st parameter of onCreateViewHolder(...) method.

see the below line in the second parameter i'm passing the ViewGroup. This will automatically match the view to its parent:

rowView=inflater.inflate(R.layout.home_custom_list, parent,false);

///the complete code is below

public View onCreateViewHolder(ViewGroup parent, int position) {
    // TODO Auto-generated method stub
    View rowView;
        LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView=inflater.inflate(R.layout.home_custom_list, parent,false);

In your adapter where you are inflating the item in onCreateViewHolder, is the second parameter of the inflate call null?.

If so change it to parent which is the first parameter in the onCreateViewHolder function signature.

View rootView = LayoutInflater.from(context).inflate(R.layout.itemLayout, parent, false);

If you need the second parameter to be null then when you get the view reference on inflating, do the following

View rootView = LayoutInflater.from(context).inflate(R.layout.itemLayout, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
rootView.setLayoutParams(lp);
return new RecyclerViewHolder(rootView);