0

I think my problem is easy but i cant find a solution for it I have 3 Fragments and i need to execute method when the first Fragment has been replaced with the second Fragment because in the first Fragment there are media player and i must release or stop it when the user move to the second fragement

I tried onPause and onStop methods in the first fragment but onPause has been called only when i move to third fragment i dont know why the Container Activity considers that first and second fragement are the same This is my Activity Code :

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main_activity)
    setupViewPager()
    tabs.setupWithViewPager(viewPager)
    setupTabIcons()
}

private fun setupTabIcons() {

    val tabOne = LayoutInflater.from(this).inflate(R.layout.custom_tab, null) as TextView
    tabOne.text = "ONE"
    tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_home_black_24dp, 0, 0)
    tabs.getTabAt(0)!!.customView = tabOne

    val tabTwo = LayoutInflater.from(this).inflate(R.layout.custom_tab, null) as TextView
    tabTwo.text = "TWO"
    tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_dashboard_black_24dp, 0, 0)
    tabs.getTabAt(1)!!.customView = tabTwo

    val tabThree = LayoutInflater.from(this).inflate(R.layout.custom_tab, null) as TextView
    tabThree.text = "THREE"
    tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_notifications_black_24dp, 0, 0)
    tabs.getTabAt(2)!!.customView = tabThree
}

private fun setupViewPager() {
    val adapter = ViewPagerAdapter(supportFragmentManager)
    adapter.addFragment(SongsFragment.newInstance(), "ONE")
    adapter.addFragment(VediosFragment.newInstance(), "TWO")
    adapter.addFragment(InfosFragment.newInstance(), "THREE")
    viewPager.adapter = adapter
}}
DoctorDoom
  • 501
  • 2
  • 8
  • 21
  • 1
    You are using `ViewPager`. That's a quite complicated [See this](https://stackoverflow.com/questions/6834518/saving-fragment-state-in-viewpager). You can use `ViewPager.OnPageChangeListener` for this. – ADM Nov 30 '18 at 16:48
  • Thank you very much that was but can i ask you if you have easier way to do this ?? – DoctorDoom Nov 30 '18 at 16:58

1 Answers1

-1

FragmentManager.OnBackStackChangedListener may help.

Implement FragmentManager.OnBackStackChangedListener in activity and in onBackStackChanged method get current fragment and check.

J.V
  • 1
  • 2