11

I am asking this cuz I am sort of curious.

1 ) Most google demos finds fragments by its ID if the fragment is already been created in xml.

So if we take that approach, the way we show fragments is by hiding it and showing it since the fragments are already created.

2) There are also examples provided by google where you can create the fragment with a constructor and inflate it. This acts weird by the way like getActivity() returns null if it is called with in that fragment.

So If i take the first approach I have to hide and show the fragments. So why does not google provide hooks to the fragments like onHide or onShow so that we can handle things properly instead if doing the clean up ourselves with functions that we implement and call explicitly.

user498584
  • 484
  • 1
  • 8
  • 14
  • This post has some relevant answers: http://stackoverflow.com/questions/10024739/how-to-determine-when-fragment-becomes-visible-in-viewpager – treesAreEverywhere Jan 27 '14 at 20:30

3 Answers3

34

If you want to hook op on onHide/onShow just override

public void onHiddenChanged(boolean hidden) {
}

in your fragment.

Thomas Ahle
  • 30,774
  • 21
  • 92
  • 114
0

By Overrinde setUserVisibleHint you can easily track it.

  @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser){
      //When fragment is visible
    }
    Log.i("my_fragment","setUserVisibleHint: "+isVisibleToUser);
}
Shohan Ahmed Sijan
  • 4,391
  • 1
  • 33
  • 39
-3

I override the function below to determine whether a fragment is shown or hidden.

@Override public void setMenuVisibility(final boolean visible)

s k
  • 4,342
  • 3
  • 42
  • 61