Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View in RecyclerView does not match parent width

I have a horizontal recyclerview:

<android.support.v7.widget.RecyclerView
        android:id="@+id/rvRecommendedVendors"
        android:scrollbars="none"
        android:layout_width="match_parent"
        android:layout_height="225dp"
        android:visibility="visible"
        android:layout_below="@+id/llRecommendedVendors"
        android:overScrollMode="never"
        android:background="@color/dark_blue"
        />

It has an item:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageButton
        android:layout_width="match_parent"
        android:layout_height="225dp"
        android:id="@+id/ibRecommendedCoverPhoto"
        android:src="@drawable/sample_cover_image"
        android:background="@android:color/darker_gray"
        android:scaleType="centerCrop"/>
</LinearLayout>

Both controls' widths are set to match_parent however, the imagebutton won't "match" its parent's width.

I logged the width:

recyclerView Height: 338
recyclerView Width: 480

This is from the recyclerview method onCreateViewHolder:

  @Override
    public RecommendedVendorsViewHolder onCreateViewHolder(ViewGroup vg, int viewType) {
    View v = LayoutInflater.from(vg.getContext()).inflate(R.layout.item_recommended_list, vg, false);

I logged the view's height and width:

View v Height: 338
View v Width: 327

I tried setting the width programmatically:

@Override
    public RecommendedVendorsViewHolder onCreateViewHolder(ViewGroup vg, int viewType) {
        View v = LayoutInflater.from(vg.getContext()).inflate(R.layout.item_recommended_list, vg, false);
        RecyclerView.LayoutParams params= (RecyclerView.LayoutParams)v.getLayoutParams();
        params.width=480;
        v.setLayoutParams(params);

        return vh;
    }

View v Height: 338
View v Width: 480

It works but I don't want to resize the view everytime.

like image 638
Kim Montano Avatar asked May 15 '15 04:05

Kim Montano


1 Answers

RecyclerView is very crappy when it comes to properly positioning it and/or its child views. Try

@Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
    final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    final View v = inflater.inflate(R.layout.item, parent, false);

    // match_parent won't work for RecyclerView (sigh)
    final ViewGroup.LayoutParams lp = v.getLayoutParams();
    lp.width = parent.getWidth();
    lp.height = parent.getHeight();
    v.setLayoutParams(lp);

    return new ViewHolder(v);
}

which basically replaces match_parent for both height & width within the child view. For your particular case you would only set the width then.

like image 155
foo Avatar answered Nov 08 '22 12:11

foo