Diyaa Hamza Diyaa Hamza - 6 months ago 379
Android Question

RecyclerView item width layout_width=“match_parent” does not match parent

I'm using RecyclerView and I'm trying to make the width item of RecyclerView match_parent since I'm using


LinearLayoutManager.HORIZONTAL


RecyclerView items after running

<android.support.v7.widget.RecyclerView
android:id="@+id/listOffersHits"
android:layout_width="match_parent"
android:layout_height="match_parent" />


custom_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight="1"
android:layout_margin="2dp"
card_view:cardCornerRadius="2dp">
<ImageView
android:id="@+id/offerImage"
android:layout_width="match_parent"
android:layout_height="match_parent"

android:background="@drawable/item_selector"
android:scaleType="fitXY"
android:src="@drawable/offer"
/>

</android.support.v7.widget.CardView>


LayoutManager

LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL, false);
listOffersHits.setLayoutManager(linearLayoutManager);


ViewHolder

View view= LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_layout, parent, false);
ViewOffersHolder viewHolder=new ViewOffersHolder(view);
return viewHolder;

Answer

I fixed the problem:

1- Get the screen size (width).

2- make the ViewHolder width same as screen size.

Below my code if any one need it.

WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        int height = windowManager.getDefaultDisplay().getHeight();
        view.setLayoutParams(new RecyclerView.LayoutParams(width, RecyclerView.LayoutParams.MATCH_PARENT));