1

Here are simple steps.

step1 : fragment1 was showing and it's already added to Backstack
step2 : fragment2 is added to Backstack and showing it now
step3 : fragment2 is removed from Backstack

So finally, fragment1 is showing again to user. In this situation, is there anyway to detect if fragment1 is showing again inner fragment1?

I tried with OnResume() but it doesn't work.

Thanks for answers!

Passionate.C
  • 233
  • 3
  • 20

4 Answers4

1
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.fragment_container);

if (currentFragment instanceof YourFragment) {

if(currentFragment.this.isVisible())
{
  //your code
}
}
sasikumar
  • 12,540
  • 3
  • 28
  • 48
1

When you add the fragment in your transaction you should use a tag.

fragTrans.replace(android.R.id.content, myFragment, "MY_FRAGMENT");

...and later if you want to check if the fragment is visible:

MyFragment myFragment = (MyFragment)getFragmentManager().findFragmentByTag("MY_FRAGMENT");
if (myFragment != null && myFragment.isVisible()) {
   // add your code here
}

See also http://developer.android.com/reference/android/app/Fragment.html


I just copied this answer https://stackoverflow.com/a/9295085/7232310 because I think is what you need. Otherwise you can check the following answers on the same question.

Hope it helps!

Community
  • 1
  • 1
Vash
  • 704
  • 1
  • 7
  • 19
  • yes. it helps but it needs to add code to Activity or something that manages the fragments. i want to detect in fragment1. – Passionate.C May 16 '17 at 08:47
0

Try onAttach(), this is to trigger if the fragment is showed. onDetach() is to detect if the fragment is leaving the user interface.

For example: you have 3 fragment(frag1,frag2,frag3), every fragment you need to put the onAttach()

frag1 
@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Toast.makeText(context, "I'm frag 1", Toast.LENGTH_SHORT).show();
    }
0

I think there are 2 options

Try to override this behaviour and see if it works

void onHiddenChanged (boolean hidden)

As per documented here

Or Other option is to onStart() / onResume() callback of lifecycle try to observe behaviour of fragments visibility state.

boolean isVisible ()

As per documented here

jignesh.world
  • 1,396
  • 1
  • 11
  • 26