【问题标题】:findViewByID returns null within FirestoreRecyclerAdapterfindViewByID 在 FirestoreRecyclerAdapter 中返回 null
【发布时间】:2019-04-14 07:58:51
【问题描述】:

我正在尝试 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>

【问题讨论】:

    标签: java android asynchronous android-recyclerview google-cloud-firestore


    【解决方案1】:

    您使用了错误的 TextView 引用,即

    标题

    当您的 XML 显示 tvTitle 而且第二个文本视图指的是错误的ID。所以你的代码应该是这样的

     tvTitle = itemView.findViewById(R.id.tvTitle);
     tvPitch = itemView.findViewById(R.id.tvPitch);
    

    【讨论】:

      【解决方案2】:

      使用此etPitch = itemView.findViewById(R.id.tvPitch); 代码。

      【讨论】:

        猜你喜欢
        • 2011-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多