0

Suppose there are two Fragments, X, and Y. I am adding Y fragment over X. When Y completes its work then removed and again X is visible.

Problem: I have to do some task when Y fragment is removed and X is visible again, but onResume is not called because it depends on Activity. Then how should I know that X Fragment is visible?

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • 2
    `Fragments` `onResume() or `onPause()` are tightly coupled to the `Activity`. They will only get called when Activity's methods get called . – ADM Jan 22 '19 at 10:16
  • Possible duplicate of [Fragment onResume() & onPause() is not called on backstack](https://stackoverflow.com/questions/11326155/fragment-onresume-onpause-is-not-called-on-backstack) – Zoe Jan 23 '19 at 18:43

2 Answers2

1

Fragment won't call onResume if you are pushing one fragment on another. You need to use onHiddenChanged method, which will be notify on fragment changed visibility

@Override
public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    if (hidden) {
        //do when hidden
    } else {
       //do when show
    }
}
Kajol Chaudhary
  • 257
  • 2
  • 9
0

In activiy you shuold use replace for second fragment:

override fun onCreate(savedInstanceState: Bundle?) {         
      supportFragmentManager.beginTransaction().add(R.id.fragContainer,                 FirstFragment()).addToBackStack(FirstFragment::class.java.simpleName).commit()
     
      btnAdd.setOnClickListener {                   
                supportFragmentManager.beginTransaction().replace(R.id.fragContainer,  
                SecondFragment()).addToBackStack(SecondFragment::class.java.simpleName).commit()
            }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        supportFragmentManager
        .popBackStack(SecondFragment::class.java.simpleName,FragmentManager.POP_BACK_STACK_INCLUSIVE)
    }

So, when you click back, SecondFragment will disappear and in FirstFragment onResume() will be called

Vladyslav Ulianytskyi
  • 1,401
  • 22
  • 22