关于RecyclerView的条目根目录设置成 Match_Parent无效的问题

今天用RecyclerView加载数据时发现条目的默认宽度竟然无法填充整个宽度,这种反人类的操作就导致了一个问题,内容无法居中并且默认左对齐。起先还以为是根布局的属性设置问题,如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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="wrap_content">

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/tv_end"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"//这个地方按理居中显示
        android:text="没有更多了..."
        android:textColor="@android:color/darker_gray" />

    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@+id/ll_loading"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="horizontal">

        <ProgressBar
            android:layout_width="30dp"
            android:layout_height="30dp" />

        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="加载中..."
            android:textColor="@android:color/darker_gray" />
    </androidx.appcompat.widget.LinearLayoutCompat>
</androidx.constraintlayout.widget.ConstraintLayout>

然后代码如下

@NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new MyFooterViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loadmore, null));
        }
    }

神奇的东西发生了,没有更多了... 几个字左对齐显示,不居中!!! 解决方式如下:

@NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
	//使用三个参数的方法
            return new MyFooterViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loadmore, parent, false));
        }
    }
posted @ 2022-09-09 16:36  呢哇哦比较  阅读(325)  评论(0)    收藏  举报