Home > database >  Set RecyclerView start position when installing the app first time
Set RecyclerView start position when installing the app first time

Time:09-14

Is there a way for me to set starting position for recyclerview, so when the user installs the app for the first time, and starts the app, the recyclerview will be shown at some position, and not from the start?

I have been using:

recyclerView.scrollToPosition(myPosition, 0)

But since the app is started for the first time, it is always default position shown in the recyclerview. The first param (myPosition) is set in the onBindViewHolder function.

I think this happens because recyclerview creates and destroys views while scrolling, so probably I would need to first iterate through the whole list, but not sure if the views will get destroyed in the end.

CodePudding user response:

You can do this, but you need some form of persistence to store if is the first time seen it.

So, first of all, you can't just scroll to the position because even if you pass the data immediately, the adapter doesn't immediately update. There is a delay.

You have to attach a RecyclerView.AdapterDataObserver to the adapter and inside there do the scrolling.

 val observer = object : RecyclerView.AdapterDataObserver() {
         override fun onChanged() {
             if (isFirstTime) {
                 //scrollToPosition
                 //mark first time as no longer first time
             }
         }
     }
     adapter.registerAdapterDataObserver(observer)

You might still need a delay, if so try with

viewlifeCycleOwner.lifeCycleScope.launch {
    delay(400)
    //scrollToPosition

}

You need to make your firstTime some form of persistence, so it remains across app-restart. I think SharedPrefferences should be enough.

CodePudding user response:

You could save and load a variable to shared preferences, and once the user scrolls for the first time, that variable would change. (Just save a boolean - isFreshInstall, set to true as default and on scroll set it to false)

Then if the variable indicates it's the first time seeing the app just use a simple if to see ifyou should use myPosition or the position you want to show.

  • Related