I have a RecyclerView
that is using a PagedListAdapter
. I want to refresh the list (ie fetch the data from my DataSource
) and scroll to the top automatically.
Here's my RecyclerView:
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
val adapter by lazy {
DiscoveryListAdapter(activity)
}
recyclerView.let {
it.adapter = adapter
it.layoutManager = LinearLayoutManager(activity)
}
Here's my Adapter:
class DiscoveryListAdapter() : PagedListAdapter<Discovery, DiscoveryListItemViewHolder>(DiscoveryDiffCallback()) {
@SuppressLint("CheckResult")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DiscoveryListItemViewHolder {
//Extension function
val view = parent.inflate(R.layout.discovery_detail_list_item)
return DiscoveryListItemViewHolder(view)
}
override fun onBindViewHolder(viewHolder: DiscoveryListItemViewHolder, position: Int) {
getItem(position)?.let {
viewHolder.populateFrom(it)
}
}
class DiscoveryDiffCallback : DiffUtil.ItemCallback<Discovery>() {
override fun areItemsTheSame(one: Discovery, two: Discovery) =
one == two
override fun areContentsTheSame(one: Discovery, two: Discovery) =
one == two
}
}
I'm building the PagedList like so, subscribing to the LiveData object that is returned and calling submitList
on the adapter:
fun buildLivePagedList(): LiveData<PagedList<Discovery>> {
val config = PagedList.Config.Builder()
.setPageSize(PAGE_SIZE)
.setEnablePlaceholders(false)
.setPrefetchDistance(PAGE_SIZE * 2)
.build()
val factory = DiscoveryListDataSourceFactory()
return LivePagedListBuilder(factory, config).build()
}
I am using this line to refresh the list:
adapter.currentList?.dataSource?.invalidate()
This seems to refresh correctly, but it leaves the list scrolled halfway down. From there I don't know how to get the recyclerview to return to the top of the list. I have tried recyclerView.scrollToPosition(0)
but no dice. No matter what, the list refreshes but does not scroll to the top. How do I do this?