LayoutInflater 忽略 XML 属性

问题描述

我的 LayoutInflater 有问题。 首先这里是我的item.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@drawable/button" >
 
</RelativeLayout>

(我删除了这个问题的所有不必要的东西)

当我像这样在 RecyclerViewAdapter 中设置我的 LayoutInflater 时:

View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,null);

一切正常,看起来我希望它是:

This is how I want it to look

在许多关于 LayouInflater 的文档和文章中,他们推荐像这样使用 LayoutInflater:

View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);

但是当我这样做时,它会忽略 item.xml 文件中的属性

enter image description here

有很多文章解释应该避免第一种方法(对我有用的方法)。 这是其中一篇文章https://web.archive.org/web/20190528213406/https://possiblemobile.com/2013/05/layout-inflation-as-intended/

这是我完整的 RecyclerView.Adapter 类:

public class AdapterTest extends RecyclerView.Adapter<AdapterTest.TestViewHolder> {


    @Override
    public TestViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,null);
        return new TestViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final TestViewHolder holder,int position) {


    }

    @Override
    public int getItemCount() {
        return 10;
    }

    public class TestViewHolder extends RecyclerView.ViewHolder {
 

        public TestViewHolder(View itemView) {
            super(itemView); 
        }
    }


}

如何使用推荐的方式,但仍然有我想要的结果?

解决方法

我通过在 onCreateViewHolder 中添加这两行来修复它:

RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
v.setLayoutParams(lp);

我的 onCreateViewHolder 现在看起来像这样:

@NonNull
@Override
public TestViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {

    View v = LayoutInflater.from(mContext).inflate(R.layout.item,parent,false);
    RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
    v.setLayoutParams(lp);
    return new TestViewHolder(v);
}

这是我从那里得到的答案: https://stackoverflow.com/a/30692398/7735807

我真的无法解释为什么它现在起作用了,因为我的 RecyclerView 从一开始就设置为 MatchParent 宽度和高度。 我很高兴它现在有效

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...