RecyclerView에서 match_parent 너비가 작동하지 않습니다


135

내 RecyclerView와 항목의 match_parent 너비가 있지만 결과는 다음과 같습니다. 여기에 이미지 설명을 입력하십시오

    <view
    class="android.support.v7.widget.RecyclerView"
    android:layout_width="match_parent"

그리고 품목 :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:id="@+id/ll_itm"
android:orientation="horizontal"
android:layout_width="match_parent"

완전한:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:id="@+id/ll_itm"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="100"
android:gravity="right"
>


<Button
    android:layout_width="0dp"
    android:layout_weight="15"
    android:layout_height="fill_parent"
    android:text="ملاحظات"
    android:id="@+id/button" />

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="20"
    android:gravity="center"
    >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <com.getbase.floatingactionbutton.FloatingActionButton
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            fab:fab_plusIconColor="#ff56ff83"
            fab:fab_colorNormal="@color/d_red"
            fab:fab_colorPressed="#ff5c86ff"
            fab:fab_size="mini"
            fab:fab_icon="@drawable/ic_remove_white"
            android:id="@+id/fab_rmv" />
        <esfandune.ir.elmikarbordiardakan.other.CustomTxtView
            android:layout_weight="25"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="0"
            android:gravity="right|center_vertical"
            android:id="@+id/txt_takhir_itm" />
        <com.getbase.floatingactionbutton.FloatingActionButton
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            fab:fab_plusIconColor="@color/colorprimarylight"
            fab:fab_colorNormal="@color/colorprimarydark"
            fab:fab_colorPressed="@color/colorprimary"
            fab:fab_size="mini"
            fab:fab_icon="@drawable/ic_add_white"
            android:id="@+id/fab_add" />

    </LinearLayout>
</LinearLayout>
    <Spinner
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="10"
        android:id="@+id/sp_nomre_itm"

        android:entries="@array/degrees"/>


<LinearLayout
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="10"
    android:gravity="center"
    >
    <!--LinearLayout baraye ine ke nameshod fab ro weight behosh dad-->
    <com.getbase.floatingactionbutton.FloatingActionButton
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        fab:fab_plusIconColor="#ff56ff83"
        fab:fab_colorNormal="@color/d_green"
        fab:fab_colorPressed="@color/d_orange"
        fab:fab_size="normal"
        fab:fab_icon="@drawable/ic_done_white"
        android:id="@+id/fab_hazr" />



</LinearLayout>
<esfandune.ir.elmikarbordiardakan.other.CustomTxtView
    android:layout_weight="5"
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="100"
    android:gravity="right|center_vertical"
    android:id="@+id/txt_ghybtNumber_itm" />

<esfandune.ir.elmikarbordiardakan.other.CustomTxtView
        android:layout_weight="30"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="عباسعلی ملاحسینی اردکانی"
        android:gravity="right|center_vertical"
        android:id="@+id/txt_title_itm"
    android:layout_marginRight="10dp"
    />

<view
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="10"
    class="de.hdodenhof.circleimageview.CircleImageView"
    android:id="@+id/view"
    android:src="@drawable/mmrdf"
   />
</LinearLayout>

답변:


434

의 항목을 팽창시키는 어댑터에서 호출 onCreateViewHolder의 두 번째 매개 변수는 ?입니다.inflatenull

그렇다면 함수 시그니처 parent의 첫 번째 매개 변수 인로 변경하십시오 onCreateViewHolder.

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

null팽창에 대한 뷰 참조를 얻을 때 두 번째 매개 변수가 필요한 경우 다음을 수행하십시오.

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);

1
작동하지 않습니다 : 항목의 rootView를 width = "match_parent"로 설정했지만 예를 들어 500dp로 설정하면 "작동"합니다. 어떤 아이디어? 좋아, LinearLayout에서는 작동하지 않지만 항목의 relativeLayout에서는 작동합니다 ... wtf?
— Cocorico

5
Sry, relativeLayout과 함께 작동하므로 LinearLayout을 RelativeLayout으로 변경합니다. 그러나 RecyclerView는 match_parent 였고 rootView 항목 (LinearLayout)도 Match_parent였으며 작동하지 않았습니다. 처음이 문제에 직면했습니다.
— Cocorico

1
아 대단해 .. 한 시간 동안 머리를 잡아 당긴 후.
— Zhi Kai

4
네, 앞서 언급했듯이 이것은 LinearLayout에서 작동하지 않았 으며이 수정으로 RelativeLayout으로 전환하면 트릭을 수행하는 것처럼 보였습니다.
— Nick Peppers

11
Linearlayout 또는 Constrainlayout에서는 작동하지 않습니다. 나는 Relativelayout으로 전환하고 작동했습니다
— ymerdrengene

18

뷰를 팽창시키는 어댑터의 onCreateViewHolder (...) 메소드 내부에서 ViewGroup을 부모로 정의해야합니다. 이것은 onCreateViewHolder (...) 메소드의 첫 번째 매개 변수에서 가져옵니다.

ViewGroup을 전달하는 두 번째 매개 변수에서 아래 줄을 참조하십시오. 그러면 뷰가 부모와 자동으로 일치합니다.

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

/// 완전한 코드는 다음과 같습니다

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);

8

너비에 FrameLayoutwith MATCH_PARENT를 사용 하고 RecyclerView+ 와 동일한 동작을 보았습니다 LinearLayoutManager. onCreateViewHolder콜백 에서 다음을 수행하기 전까지는 위의 변경 사항 중 어느 것도 효과가 없었습니다 .

@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);
}

RecyclerView 구현의 버그처럼 보입니다.


layoutParams 재정의가 나를 돕는 유일한 솔루션이었습니다. 이것이 RecyclerView의 버그인지 아는 사람이 있습니까? Google 버그 추적기에 대한 링크에 감사드립니다.
— soshial

5

어댑터에서 항목의 레이아웃 매개 변수를 설정할 때 이것을 시도하십시오.

 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;

5

나는 이렇게 고쳤다. 루트 활동 레이아웃으로 ConstraintLayout을 사용하고 있기 때문에 활동 레이아웃 파일에 문제가 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">

    <include
        android:id="@+id/toolBar"
        layout="@layout/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@color/accent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/toolBar" />
</android.support.constraint.ConstraintLayout>

2
믿기 ​​어렵지만 주변의 ConstraintLayout을 LinearLayout으로 바꾸면이 문제도 해결되었습니다.
— fjc

ConstraintLayout의 직접적인 자식에는 match_parent를 사용해서는 안됩니다. 대신 constraintLeft / Right / Bottom / Top 특성과 함께 0dp를 사용하십시오.
— DoruAdryan

3

필자의 경우 문제는 RecyclerViewXML 선언에 layout_width있었고 0dp 였는데, 이는 match_constraints를 의미합니다.로 변경하면 match_parent항목이 모든 RecyclerView너비 를 채우기 시작했습니다 .

<androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="0dp"  <-- changed this to "match_parent"
            android:layout_height="0dp"
            android:layout_marginBottom="45dp"
            android:background="@android:color/transparent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintHeight_default="wrap"
            app:layout_constraintHeight_max="360dp"
            app:layout_constraintHeight_min="60dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/header"/>

2

나는 이것을 해결했다 :

 myInflatedRowLayout.getLayoutParams().width = vg.getWidth();

MATCH_PARENT를의 실제 너비로 바꿉니다 RecyclerView.


1

이것은 나를 위해 일했습니다.

이것을 교체

   View view = View.inflate(parent.getContext(), R.layout.row_timeline, null);
   return new TimeLineViewHolder(view, viewType);

이로 인해

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

0

전체 코드를 볼 수는 없지만 LinearLayout 내부의 일부 뷰는 ' wrap_content' 인 것으로 추측 할 수 있습니다 . ' android:layout_weight="1"' 를 사용하여 하나 또는 일부를 전체 너비로 확장해야합니다.

업데이트 : 많은 중복이 layout_weight있습니다. 모두 ' wrap_content'로 만들고 layout_weight=1마지막 CustomTextView에 대해 하나만 추가하십시오 . 이렇게하면 모든 빈 공간을 차지하게됩니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.