Подтвердить что ты не робот

Ширина match_parent не работает в RecyclerView

My RecyclerView и элемент имеют ширину match_parent, но результат: enter image description here

    <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>
4b9b3361

Ответ 1

В вашем адаптере, где вы раздуваете элемент в onCreateViewHolder, является вторым параметром вызова inflate null?.

Если это так, измените его на 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);

Ответ 2

Внутри 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);

Ответ 3

попробуйте это, когда вы установите параметры макета для вашего элемента в адаптере.

 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;

Ответ 4

Я использовал FrameLayout с 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.

Ответ 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>

Ответ 6

Я решил это с помощью:

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

Он заменяет MATCH_PARENT фактической шириной RecyclerView.

Ответ 7

Не могу видеть ваш полный код, но можно догадаться, что некоторые из видов внутри вашего LinearLayout являются "wrap_content". Вы должны сделать один или несколько из них расширенными до полной ширины, используя 'android:layout_weight="1"'

обновление: у вас много избыточных layout_weight. Сделайте все "wrap_content", и только для одного из них добавьте layout_weight=1 - для последнего CustomTextView. Таким образом, он будет занимать все пустое пространство.

Ответ 8

Это сработало для меня.

замени это

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

Ответ 9

В моем случае проблема была в объявлении RecyclerView XML, layout_width было 0dp, что означает ограничения соответствия, когда я изменил его, чтобы элементы match_parrent начали заполнять всю ширину RecyclerView:

<androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="0dp"  <-- changed this to "match_parrent"
            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"/>