java - findViewByID 在 FirestoreRecyclerAdapter 中返回 null
问题描述
我正在尝试 FirestoreRecyclerAdapter,并且数据正在加载并且可以在调试器中看到就好了。但是,当我尝试将 TextView 设置为等于某些数据时,它会崩溃,因为 TextView 为空。
调试时,它首先尝试使用 findViewById 设置 TextView,但失败并设置为 null。
我已经看到使用 onFinishInflate 的建议,但不确定在这种情况下我可以在哪里覆盖该函数。
public class PostAdapter extends FirestoreRecyclerAdapter<Post, PostAdapter.PostHolder> {
public PostAdapter(@NonNull FirestoreRecyclerOptions<Post> options) {
super(options);
}
@NonNull
@Override
public PostHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.post_layout,
viewGroup, false);
return new PostHolder(v);
}
class PostHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvPitch;
public PostHolder(@NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.etTitle);
tvPitch = itemView.findViewById(R.id.etPitch);
}
}
@Override
protected void onBindViewHolder(@NonNull PostHolder holder, int position, @NonNull Post model) {
holder.tvTitle.setText(model.title);
holder.tvPitch.setText(model.pitch);
}
}
_________________________________________________
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="@+id/tvPitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
解决方案
您使用了对 TextView 的错误引用,即
标题
而您的 XML 显示 tvTitle 并且第二个 textview 指的是错误的 Id。所以你的代码应该是这样的
tvTitle = itemView.findViewById(R.id.tvTitle);
tvPitch = itemView.findViewById(R.id.tvPitch);
推荐阅读
- mysql - 'where 子句'中的未知列'item.Item_id'?
- sql - 当涉及到设置记录类型的表并且每种类型都有不同的字段时,如何在TSQL中设计一组表?
- angular - Ngb 日期选择器 minDate 和 maxDate 未按预期工作
- multithreading - 如果我不加入主线程,为什么要线程转储核心
- flutter - 防止 AlertDialog 方法在返回值之前退出
- d3.js - 如何获得 d3 线的坐标?
- oop - 在一行中为类接口创建实例?
- mysql - 表和视图继续在 MYSQL 中获取
- dynamics-crm - 如何解决这个错误(Server Is Busy 记录已保存。但是由于服务器忙,数据无法显示)
- android - Cordova 的 device.uuid 值可以用于发送 Firebase 推送通知吗?