Home > database >  How to Keep selected tab in tablayout even after came back to the page in android kotlin
How to Keep selected tab in tablayout even after came back to the page in android kotlin

Time:12-07

I have 3 fragments in my tab layout . When I select 2nd fragment in my tab layout in that second fragment I'm clicking view all for the second fragment.. After enter into 2nd fragment view all , I'm clicking back button. At the time in my tab layout it goes to 1st fragment not stayed in the second fragment. I need to stay in the selected fragment.. Please help me how to do this.

private const val NUM_TABS = 3
class ViewPageAdapter (fragmentManager: FragmentManager, lifecycle: Lifecycle) :
    FragmentStateAdapter(fragmentManager, lifecycle) {

    override fun getItemCount(): Int {
        return NUM_TABS
    }

    override fun createFragment(position: Int): Fragment {
        return when (position) {
            0 -> {
                TodayFragment()
            }
            1 -> {
                UpcomingFragment()
            }
            else -> {
                PastFragment()
            }
        }
    }
}

CodePudding user response:

In your 2nd fragment use add fragment instead of replace fragment. You can have a look here to compare add fragment and replace fragment

CodePudding user response:

You need to store the tab index once you click it. So if you click the tab at index 0, save that value to sharedpreferences. when you return back to the tab with your back button, in your oncreate method of the fragment, read the value in shared preferences and use if else condition to find what the saved index was. After you get a match in your if else, programatically re-select the tab.

  • Related