Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CardView layout_width="match_parent" does not match parent RecyclerView width

The docs for inflate:

Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.

Parameters
resource ID for an XML layout resource to load (e.g., R.layout.main_page) root
view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)
attachToRoot Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML. Returns The root View of the inflated hierarchy. If root was supplied and attachToRoot is true, this is root; otherwise it is the root of the inflated XML file.

It is important here to not supply true, but do supply the parent:

LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_listitem, parent, false);

Supplying the parent View lets the inflater know what layoutparams to use. Supplying the false parameter tells it to not attach it to the parent just yet. That is what the RecyclerView will do for you.


Use RelativeLayout as the immediate parent to CardView.

<RelativeLayout 
    android:layout_width="match_parent" ... >
    <CardView 
        android:layout_width="match_parent" ... >
    </CardView>
</RelativeLayout>

This worked for me,

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

The way I did it is:

View view = mInflater.inflate(R.layout.row_cardview, null, true);
            WindowManager windowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
            int width = windowManager.getDefaultDisplay().getWidth();
            view.setLayoutParams(new RecyclerView.LayoutParams(width, RecyclerView.LayoutParams.MATCH_PARENT));

Explanation: In your onCreateViewHolde once you get card view, get the screen width and then set the layout param accordingly for card view.


This appears to be fixed in 'com.android.support:recyclerview-v7:23.2.1'

See: RecyclerView wrap_content for further discussions.