我正在构建一个应用程序,用户可以在其中收藏一些物品。我在片段内的recyclerview中显示此内容。用户还可以通过单击删除按钮从收藏夹项目列表中删除该项目。我面临的问题是,如果用户删除并在列表末尾添加项目,则recylerview会重新加载并从头开始显示。我正在使用MVVM和Livedata。这是我的代码
FragmentFavorite.kt
class FavoriteFragment :Fragment() {
lateinit var favoriteViewModel: FavoriteViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onAttach(context: Context) {
super.onAttach(context)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val v=inflater.inflate(R.layout.fragment_favorite,container,false)
favoriteViewModel=ViewModelProvider(requireActivity()).get(FavoriteViewModel::class.java)
val recylerview=v.findViewById<RecyclerView>(R.id.recylerviewFav)
recylerview.layoutManager=LinearLayoutManager(requireContext(),RecyclerView.VERTICAL,false)
favoriteViewModel.getAll(requireContext()).observe(requireActivity(), Observer {
val adapter=FavoriteAdapter(it,requireContext(),object:FavoriteDeleteListener{
override fun OnFavDelete(id: Int) {
favoriteViewModel.deleteFav(requireContext(),id)
}
})
recylerview.adapter=adapter
})
return v
}
}
RecylerviewAdapter.kt
class FavoriteAdapter(val list:List<Favorite>,context: Context,val listener:FavoriteDeleteListener) :RecyclerView.Adapter<FavoriteAdapter.MyViewholder> (){
val listofFav=list.reversed()
class MyViewholder(itemview: View):RecyclerView.ViewHolder(itemview) {
val textview_src=itemview.findViewById<TextView>(R.id.textview_src)
val textView_tar=itemView.findViewById<TextView>(R.id.textview_tar)
val delte_fav=itemview.findViewById<ImageView>(R.id.delete_fav)
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): FavoriteAdapter.MyViewholder {
val v=LayoutInflater.from(parent.context).inflate(R.layout.fav_list,parent,false)
return MyViewholder(v)
}
override fun onBindViewHolder(holder: FavoriteAdapter.MyViewholder, position: Int) {
holder.textView_tar.text=listofFav[position].translated_text
holder.textview_src.text=listofFav[position].text_to_translate
holder.delte_fav.setOnClickListener {
listofFav[position].fid?.let { it1 -> delete(it1,listener)
notifyItemRemoved(position)
}
}
}
override fun getItemCount(): Int {
return listofFav.size
}
fun delete(id:Int,listene: FavoriteDeleteListener) {
listene.OnFavDelete(id)
}
}
答案 0 :(得分:0)
我怀疑问题出在这里
favoriteViewModel.getAll(requireContext()).observe(requireActivity(), Observer {
val adapter=...
recylerview.adapter=adapter
})
如果从数据集中删除某项导致观察者发出新数据集,则将重新分配RecyclerView
的适配器,这将完全重置视图位置。
您可以使用the ListAdapter
component来计算列表之间的差异,而不是完全覆盖适配器的所有内容。