RecyclerView wraps its conent

Viewed 82

I am using the RecyclerView to inflate a Linear Vertical listViews, However, although the width of a child is set to match_parent, RecyclerView wraps that at runtime.

Here is a screenshot of the problem:

enter image description here

item_recyclerView

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

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tag_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="0dp"
            android:maxLines="2"/>
        <TextView
            android:id="@+id/tag_role"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <com.google.android.material.imageview.ShapeableImageView
        android:id="@+id/user_pic"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_weight="0"
        android:rotation="-45"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_user"
        app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.App.circleImageView" />

</LinearLayout>
2 Answers

When inflating a layout file, the layout_ attributes on the root view will be ignored unless you specify a parent ViewGroup in the inflate() call. You are not currently doing so.

In your onCreateViewHolder() method, replace this:

ItemQuestionPostBinding binding = ItemQuestionPostBinding.inflate(inflater);

with this:

ItemQuestionPostBinding binding = ItemQuestionPostBinding.inflate(inflater, parent, false);

Note also that you probably don't want to be using match_parent for the height of your RecyclerView's items:

android:layout_width="match_parent"
android:layout_height="match_parent"

This will give the appearance that only a single item is visible in your RecyclerView, since each item will be the full height of the screen. This is currently not a problem for the exact same reason that the match_parent width is being ignored.

give for your parent linearlayout weightSum 5 give for imageView weight 1 and do his width 0 and for child linearlayout weight 4

enter code here
Related