0

I'm using paging 3 to paginate my items and then show them in recycler view. but there's a time that the first item change. for example, consider the situation below:

item A
item B
item C

after a while, for some reason, data gets update and list order changes to like bellow:

item B
item A
item C

my problem is:

recycler view stays exactly in its last position. I mean when update apply, item B will go to the first position but recycler view won't scroll to the top, it just states pointing to item A, and the user won't notify that item B has changed,

how can I set that recycler view scroll automatically just when the first item changed?

here is part of my adapter:

class TicketListAdapter :  PagingDataAdapter<TicketListModel, TicketListAdapter.ViewHolder>(
   diffCallback =      object : DiffUtil.ItemCallback<TicketListModel>() {
       override fun areItemsTheSame(oldItem: TicketListModel, newItem: TicketListModel): Boolean {
           return oldItem.ticket_id == newItem.ticket_id
       }
       override fun areContentsTheSame(
           oldItem: TicketListModel,
           newItem: TicketListModel
       ): Boolean {
           return oldItem == newItem
       }

   }
){

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.ticket_list_item_model, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int)= holder.bind(getItem(position))

and here shows how I use my recycler view and data:

 binding.recyclerView.apply {
            this.adapter = adapter
            this.layoutManager = LinearLayoutManager(requireContext())
        }
        viewModel.tickets.observe(viewLifecycleOwner, {
            viewLifecycleOwner.lifecycleScope.launch {
                adapter.submitData(it)
            }
        })

I also try that set observer but it didn't work:

        adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
            override fun onChanged() {
                super.onChanged()
                if (adapter.getItemId(0) != firstItemId) {
                    binding.recyclerView.smoothScrollToPosition(0)
                    firstItemId = adapter.getItemId(0)
                }
            }

the firstItemId is initialized with value -1;

mohammad
  • 187
  • 1
  • 2
  • 15

1 Answers1

0

Calling adapter.notifyDataSetChanged() will make the recyclerview to reload, then your items should adjust.

Regarding scrolling (dublicate), have a look here: Scroll RecyclerView to show selected item on top

Tobi
  • 858
  • 7
  • 15
  • 1
    no, I don't think that is the answer, I just need to scroll to the first position when the first item of recycler view has changed. I don't need to call adapter.notifyDataSetChanged() because paging library will handle that. – mohammad Nov 08 '20 at 16:38