recyclerView 的片段错误(上下文)

Error in fragment with recyclerView (context)

我正在使用带有 SDK 版本 29 的 Kotlin。 我在几个网站上搜索过,但没有找到关于这个主题的任何内容。 我想使用适配器在我的片段中使用 recyclerview,但是我无法解决关于我的适配器的错误。

这是错误:

类型不匹配:推断的类型是 Flux 但上下文是预期的

来自片段的下一行:

适配器 = PostsAdapter(this, posts)

你知道如何设置上下文吗?

这是我的代码:

适配器:

导入:

import android.content.Context 
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.givenaskv1.R
import kotlinx.android.synthetic.main.item_post.view.*

代码:

class PostsAdapter (val context: Context, val posts : List<Post>) :
    RecyclerView.Adapter<PostsAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.item_post, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount() = posts.size
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(posts[position])
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(post: Post) {
            itemView.tvUsername.text = post.user?.firstName
            itemView.tvDescription.text = post.description
            Glide.with(context).load(post.imageUrl).into(itemView.ivPost)
            itemView.tvRelativeTime.text = DateUtils.getRelativeTimeSpanString(post.creationTimeMs)
        }
    }
}
 

片段:

导入:

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.givenaskv1.R
import com.example.givenaskv1.models.Post
import com.example.givenaskv1.models.PostsAdapter
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
import kotlinx.android.synthetic.main.fragment_flux.*

代码:

private const val TAG = "Flux"
class Flux : Fragment() {

    private lateinit var firestoreDb : FirebaseFirestore
    private lateinit var posts : MutableList<Post>
    private lateinit var adapter: PostsAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


    posts = mutableListOf()
    adapter = PostsAdapter(this, posts)  <----- HERE IS THE ERROR
    rvPosts.adapter = adapter
    rvPosts.layoutManager = LinearLayoutManager(this.context)


    firestoreDb = FirebaseFirestore.getInstance()
    val postsReference = firestoreDb.collection("post")
        // .limit() indique le nombre de post MAXIMIM a afficher en même temps, pour éviter le lagg
        .limit(20)
        // .orderBy() filtre selon le critère choisi (ici par ordre chonologique)
        .orderBy("creation_time_ms", Query.Direction.DESCENDING)

    postsReference.addSnapshotListener{ snapshot, exception ->

        if (exception != null || snapshot == null) {
            Log.e(TAG, "Exception when querying posts", exception)
            return@addSnapshotListener
        }
        val postList = snapshot.toObjects(Post::class.java)
        posts.clear()
        posts.addAll(postList)
        adapter.notifyDataSetChanged()

        for (post in postList) {
            Log.i(TAG, "Post ${post}")
        }
    }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_flux, container, false)
    }
}

fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Flux.Flux">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvPosts"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

当我尝试替换时

adapter = PostsAdapter(this, posts)

adapter = PostsAdapter(requireContext(), posts)

出现以下错误:

java.lang.IllegalStateException: rvPosts 不能为空

非常感谢!

这是因为您在创建片段视图之前在片段 onCreate 回调中获得了 RecyclerView 实例;由于 onCreate() 回调在 onCreateView() 回调

之前触发

注意:片段视图由 onCreateView() 创建并返回。

要解决此问题,请将代码从 onCreate() 转移到 onCreateView()

private const val TAG = "Flux"
class Flux : Fragment() {

    private lateinit var firestoreDb : FirebaseFirestore
    private lateinit var posts : MutableList<Post>
    private lateinit var adapter: PostsAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

        val view = inflater.inflate(R.layout.fragment_flux, container, false)

        posts = mutableListOf()
        adapter = PostsAdapter(requireContext(), posts) 
        
        val rvPosts = view.findViewById<RecyclerView>(R.id.rvPosts)
        rvPosts.adapter = adapter
        rvPosts.layoutManager = LinearLayoutManager(this.context)


        firestoreDb = FirebaseFirestore.getInstance()
        val postsReference = firestoreDb.collection("post")
            // .limit() indique le nombre de post MAXIMIM a afficher en même temps, pour éviter le lagg
            .limit(20)
            // .orderBy() filtre selon le critère choisi (ici par ordre chonologique)
            .orderBy("creation_time_ms", Query.Direction.DESCENDING)

        postsReference.addSnapshotListener{ snapshot, exception ->

        if (exception != null || snapshot == null) {
            Log.e(TAG, "Exception when querying posts", exception)
            return@addSnapshotListener
        }
        val postList = snapshot.toObjects(Post::class.java)
        posts.clear()
        posts.addAll(postList)
        adapter.notifyDataSetChanged()

        for (post in postList) {
            Log.i(TAG, "Post ${post}")
        }
        return view
    }
}