我在android studio中使用RecycleView。当数据来自Firebase时,最初是正确的。后来,当我向List()类型的列表添加1条短信时,我得到了错误的数据。例如:如果列表是{1,2,3,4,5},在屏幕上的列表中添加6。列表{1,2,3,4,5,6}的元素应该按照这个顺序出现。在这种情况下,追赶后列表{1,2,3,4,5,1,2,3,4,5,6}是这样的。经过1次更新后,它工作正常。
class ChatAdapter(var list:MutableList<Sms>,var context: Context):RecyclerView.Adapter<RecyclerView.ViewHolder>(){
companion object {
private const val ITEM_RECEIVE = 1
private const val ITEM_SENT = 2
}
private val shared by lazy {
SharedPref(context)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == 1) {
val view = LayoutInflater.from(context).inflate(R.layout.item_he_sms, parent, false)
ReceiveVewHolder(view)
}else{
val view = LayoutInflater.from(context).inflate(R.layout.item_my_sms, parent, false)
SentViewHolder(view)
}
}
override fun getItemViewType(position: Int): Int {
val currentMessage = list[position]
return if (currentMessage.emailAddress==shared.getEmail()){
ITEM_SENT
}else{
ITEM_RECEIVE
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (shared.getEmail()==list[position].emailAddress){
holder as SentViewHolder
holder.textView.text = list[position].smsText
}else{
holder as ReceiveVewHolder
holder.textView.text = list[position].smsText
if (list[position].gender=="Male"){
holder.imagePerson.setImageResource(R.drawable.male_avatar)
}else{
holder.imagePerson.setImageResource(R.drawable.female_avatar)
}
}
}
override fun getItemCount(): Int =list.size
inner class SentViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView: TextView = view.findViewById(R.id.my_message)
}
inner class ReceiveVewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView: TextView = view.findViewById(R.id.he_message)
val imagePerson:CircleImageView=view.findViewById(R.id.imagePerson)
}
}
2条答案
按热度按时间pod7payv1#
在适配器中创建此方法:
然后从
observer
方法内部调用它,它应该可以解决您的问题。az31mfrm2#
Xato Firebase'和getAllSms数据,sendSms()通常是空的,{1,2,3,4,5,1,2,3,4,5,6}返回结果。调用数据更改列表中的旧数据。清除旧数据。