为什么我的Recyclerview在随机位置添加新项目?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么我的Recyclerview在随机位置添加新项目?相关的知识,希望对你有一定的参考价值。

在阅读了很多关于如何在顶部(或底部)添加项目的文章后,我意识到 list.add(position, item) 与...一起 notifyDataSetChanged() 是在顶部(索引0)添加项目的正确方法。然而,在我的代码中,即使这样做了,我的RecyclerView也会在随机的地方添加位置。下面是我的CommentsActivity代码。

class CommentsActivity : AppCompatActivity() {

private var clickedPostUid = ""
private var currentUserUid = ""
private lateinit var binding_commentsActivity: ActivityCommentsBinding
private val currentUserUID = FirebaseAuth.getInstance().currentUser?.uid!!
private val dbRef = FirebaseDatabase.getInstance().reference
private val uidRef = currentUserUID.let { dbRef.child("Users").child(it) }
private var commentAdapterView: CommentsAdapter? = null
private var commentsList: MutableList<CommentsModel>? = null
var commentsActivityRecyclerView: RecyclerView? = null

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

    binding_commentsActivity = ActivityCommentsBinding.inflate(layoutInflater)
    clickedPostUid = intent.getStringExtra("keyIdentifierPostUid")!!
    currentUserUid = intent.getStringExtra("keyIdentifierCurrentUserUid")!!

    commentsActivityRecyclerView =
        binding_commentsActivity.commentsActivityRecyclerView


    val layoutManager = LinearLayoutManager(this)
    layoutManager.reverseLayout = true
    layoutManager.stackFromEnd = true

    commentsActivityRecyclerView!!.layoutManager = layoutManager

    commentsList = ArrayList()
    commentAdapterView = CommentsAdapter(this, commentsList as ArrayList<CommentsModel>)
    commentsActivityRecyclerView!!.adapter = commentAdapterView
    commentsActivityRecyclerView!!.setHasFixedSize(true)

    LoadAndDisplayComments()

而这是我的LoadAndDisplayComments()

private fun LoadAndDisplayComments() {
    val commentsRef = dbRef.child("Comments").child(clickedPostUid)

    commentsRef.addValueEventListener(object : ValueEventListener {
        override fun onCancelled(p0: DatabaseError) {
            TODO("Not yet implemented")
        }

        override fun onDataChange(p0: DataSnapshot) {
            if (p0.exists())
            {
                commentsList!!.clear()
                for (snapshot in p0.children)
                {
                    val getCommentDetails = snapshot.getValue(CommentsModel::class.java)
                    if (getCommentDetails != null) {
                        commentsList!!.add(0,getCommentDetails)
                    }
                }

                commentAdapterView!!.notifyDataSetChanged()
            }
            else{
                Toast.makeText(this@CommentsActivity, "No comments" , Toast.LENGTH_SHORT).show()
            }
        }
    })
}

这是我的评论适配器

class CommentsAdapter(
private var commentsContext : Context,
private var commentsList: MutableList<CommentsModel>
) : RecyclerView.Adapter<CommentsAdapter.CommentsViewHolder>()
{
inner class CommentsViewHolder(@NonNull itemView: View) : RecyclerView.ViewHolder(itemView) {
    val showComment : TextView = itemView.comments_recview_item_comment
    val showImage : CircleImageView = itemView.comments_recview_item_profile_image
    val showUsername : TextView = itemView.comments_recview_item_username

}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentsViewHolder {
    val itemView = LayoutInflater.from(commentsContext)
        .inflate(R.layout.comment_recyclerview_item, parent, false)

    return CommentsViewHolder(itemView)
}

override fun getItemCount(): Int {
    return commentsList!!.size
}

override fun onBindViewHolder(holder: CommentsViewHolder, position: Int) {

    val currentUser = FirebaseAuth.getInstance().currentUser!!
    val comment = commentsList!![position]
    holder.showComment.text = comment.comment
}

我需要一个新的评论显示在回收视图的顶部或底部。我知道如何使用 .SmoothScroll. 如果需要的话,我很乐意发布XML。谢谢你。

答案

原来错误不在RecyclerView。是我在数据库中存储值的方式。我在Firebase中为我的值创建了一个唯一的Id,导致了错误。相反,我使用.push来生成唯一的键,它工作得很好。

错误的方法(或者说不是我想要的)。

val uniqueCommentId = UUID.randomUUID().toString()
        .replace("-","").toUpperCase(Locale.ROOT)
    val postCommentsRef = FirebaseDatabase.getInstance().reference
        .child("Comments")
        .child(postId).child(uniqueCommentId )
   postCommentRef.setValue()

更好的方法:

 val postCommentsRef = FirebaseDatabase.getInstance().reference
        .child("Comments")
        .child(postId)

    val commentMap = HashMap<String, Any>()
    commentMap["userUid"] = currentUserUid
    commentMap["postId"] = postId
    commentMap["comment"] = comment

    postCommentsRef.push().setValue(commentMap)

在这之后,我的工作很顺利。

以上是关于为什么我的Recyclerview在随机位置添加新项目?的主要内容,如果未能解决你的问题,请参考以下文章

在 RecyclerView 的第一个索引处添加项目并调用 notifydatasetchange 后如何保持在滚动位置

SnapHelper 项目位置

拖放 RecyclerView 的第一项会移动几个随机位置

为recyclerview更新帖子的评论数

如何在 RecyclerView 项目更改上触发 MainActivity 映射修改

recyclerview 中的 Diffutil,如果添加了新项目,则使其自动滚动