回收者视图android

时间:2018-07-02 14:32:06

标签: android android-recyclerview kotlin

每当更改适配器的onbind函数中的值时,都会添加一个新项

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.postItemTitle.text= items[position].title
    var post:Post=items[position]
    val user_id=1
    var user_liked=post.users_liked
    if(user_liked.contains(user_id)){
        post.liked=true
    }
    if(post.liked){
        holder.postLikeBtn.setImageDrawable(context.resources.getDrawable(R.drawable.likered))
        holder.postLikes.text=(post.likes).toString()
    }
    else{
        holder.postLikes.text=(post.likes).toString()
    }
    holder.postLikeBtn.setOnClickListener {
        if(post.liked){
            //change color of like btn
//                holder.postLikeBtn.setImageDrawable(context.resources.getDrawable(R.drawable.likebtn))
                //set post as unliked
                post.liked=false
                //remove user from list of users that liked post
                user_liked.remove(user_id)
                //update the database
                var likes=post.likes--
                holder.postLikes.text=(likes).toString()
                val ref= FirebaseDatabase.getInstance().getReference("post")
                ref.child(post.key).setValue(post)
            }
            else{
                //update post that u liked
                post.liked=true
                user_liked.add(user_id)
                //make button red
                holder.postLikeBtn.setImageDrawable(context.resources.getDrawable(R.drawable.likered))
                //increase no of likes
                var likes=post.likes++
                holder.postLikes.text=(likes).toString()
                items[position]=post
                //update database

            val ref= FirebaseDatabase.getInstance().getReference("post")
            ref.child(post.key).setValue(post)
        }
        items[position]=post
        this.notifyDataSetChanged()
    }
}

1 个答案:

答案 0 :(得分:0)

实际上,您这样做是完全错误的。这是article的处理RecyclerView的方法。

基本上,您不会处理<!-- code with jquery-2.2.0.min.js --> <div id="gallery"> <!-- load jquery-1.3.0.min.js just on this div --> </div> <!-- load jquery-2.2.min.js again to the rest of the site --> 内的任何ui / data,它专用于将数据传递给实际的类,该类从onBindViewHolder扩展并覆盖RecyclerView.ViewHolder方法。有关更多详细信息,请参见文章。