I am using the following method to switch between Fragments (in my NavigationDrawer) by showing / hiding them.
protected void showFragment(int container, Fragment fragment, String tag, String lastTag, boolean addToBackStack ) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
if ( lastTag != null && !lastTag.equals("")) {
Fragment lastFragment = fragmentManager.findFragmentByTag( lastTag );
if ( lastFragment != null ) {
transaction.hide( lastFragment );
}
}
if ( fragment.isAdded() ) {
transaction.show( fragment );
}
else {
transaction.add( container, fragment, tag );
}
if ( addToBackStack ) {
transaction.addToBackStack( tag );
}
transaction.commit();
// set the active tag
activeFragTag = tag;
}
What I am unclear about is which method of the Fragments lifecycle is called when I show or hide it? (since there is no method such as onShow() or onHide() im not quite sure what to use). I want to perform specific actions upon showing and hiding a certain Fragment.
Just try this in your setUserVisibleHint()
And create this code in onCreateView() :
Of course you could override
setUserVisibleHint
orsetMenuVisibility
but if you need to accessContext
orActivity
, they will be null in there! There is another methodonStart
which always has the context available at hand, but it will only get called once upon creation of fragment and if you start moving between your fragments in a pager you will see that it won't get called in second view and afterwards.So... what to do now?
The workaround is quite easy, use
onStart
for the first visit andsetMenuVisibility
for later ones. Your code will probably look like below :Fragment class:
This way
Context
will always be available todoSth()
method.setUserVisibleHint
call beforeonCreateView
. and you can't update any View inside setUserVisibleHint I usefor visibility and onHiddenChanged() didn't call for the first time. it calls when the hidden state changes. because a
fragment is visible by default
. In order to achieve this method for the first time you have to callmFragmentTransaction.hide(oldFragment)
then it will workNote
if you want to use setUserVisible hint and update View Use this method
//first of all you create a interface
//After that this interface implement inside Fragment like that
// Now goes your Activity then create object of interface and call inside when addOnViewpagerListener
I @Override this method and resolve my problem:
off-course you can @Overriede following method to do so: