【发布时间】:2021-02-01 10:29:52
【问题描述】:
我的 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);
在许多关于 LayouInflater 的文档和文章中,他们建议像这样使用 LayoutInflater:
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
但是当我这样做时,它会忽略 item.xml 文件中的属性:
那里有很多文章解释应该避免第一种方法(为我工作的方法)。 这是其中一篇文章: 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);
}
}
}
我怎样才能使用推荐的方式,但仍然有我想要的结果?
【问题讨论】:
-
是我自己还是这些图片都一样?
-
@SlothCoding 我的错,现在更新第二张图片
-
尝试在根视图上的 item.xml 上使用边距,在您的情况下是RelativeLayout。这样每个项目之间都会有空间。然后就选择第二个选项。
-
@SlothCoding 它现在修复了重叠,但仍然有一个奇怪的行为,右边有 0 边距,但左边有很多。
-
@SlothCoding 感谢您尝试帮助我,我找到了解决方案并发布了答案。
标签: android xml android-recyclerview adapter layout-inflater