1

I'm using viewpager2 with navigation component. When I click on one item in viewpager, it goes to another fragment, but when I go back to previous fragment with viewpager, the position of viewpager resets to the first one. How can I keep the viewpager position when navigating to other fragment?

Mehranjp73
  • 85
  • 1
  • 7

1 Answers1

0

The best way to accomplish what you want is to have a viewmodel that will save your viewpager position.

In your fragment:


private lateinit var viewModel : TestViewModel

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

viewModel = ViewModelProvider(this).get(TestViewModel::class.java)

#### all other regular fragment stuff still aplies

}


fun setViewPager(){

        ### regular VP2 code here (adapter, etc)

viewModel.viewPagerSelected.observe(viewLifecycleOwner, Observer { page ->
                viewPager.currentItem = page
            })

viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {

            override fun onPageSelected(page: Int) {
                viewModel.updatePageSelected(page)
            }
}

ViewModel

class TestViewModel() : ViewModel() {

    private val _viewPagerSelected = MutableLiveData<Int>()
    val viewPagerSelected: LiveData<Int> = _viewPagerSelected

    fun updatePageSelected(newSelection: Int) {
        _viewPagerSelected.postValue(newSelection)
    }

}

I hope it helps!

  • is the **viewPager.currentItem = page** placed after the adapter/data is set? – Henrique Vasconcellos May 12 '20 at 18:16
  • After. It works with `viewpager.setCurrentItem(page, false)` but viewpager lags a lot. – Mehranjp73 May 12 '20 at 22:37
  • have you tried set the flag to true? This flag refers to "smooth scroll" it shouldnt matter in your case, it should set the item anyways. – Henrique Vasconcellos May 12 '20 at 22:44
  • Are you using the latest viewpager2 library? I have this repo working just fine, take a look https://github.com/chenriquevz/PokeDex/blob/master/app/src/main/java/com/chenriquevz/pokedex/ui/pokemon/PokemonFragment.kt https://github.com/chenriquevz/PokeDex/blob/master/app/src/main/java/com/chenriquevz/pokedex/ui/pokemon/PokemonViewModel.kt – Henrique Vasconcellos May 12 '20 at 22:58