Reputation: 2069
Each time my fragment become visible to the user I want to execute a peace of code that will call a web service, fetch some data and display it on the screen. I got the web service part etc working but not sure in what event I must add my code.... I tried:
But my code doesn't fire everytime.
Am using the Android v4 comp lib with SherlockFragment as my base class.
Upvotes: 4
Views: 9585
Reputation: 1840
onResume()
is called every time your fragment becomes visible to the user. There is something else wrong with your code if it doesn't
onCreateView()
is called the first time the fragment needs to draw its UI
Update: This accepted answer was working 5 years ago - it doesn't anymore
Upvotes: -17
Reputation: 2474
Below method is used determine when Fragment becomes visible in the front of a user.
private boolean loding= false; // your boolean flage
@Override
public void setUserVisibleHint(boolean isFragmentVisible) {
super.setUserVisibleHint(true);
if (this.isVisible()) {
// we check that the fragment is becoming visible first time or not
if (isFragmentVisible && !loding) {
//Task to doing while displaying fragment in front of user
loding = true;
}
}}
Upvotes: 2
Reputation: 454
This may be very old but I found setUserVisibleHint() didn't work for many of my use cases. Instead I had to resort to a hack using the ViewTreeObserver.
Basically, after your fragment is initialised, you get a view within it and do the following:
myViewInFragment.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
myMethodWhenFragmentFirstBecomesVisible();
myViewInFragment.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}
Upvotes: 3
Reputation: 538
You can use
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) { }
else { }
}
Have a look at this
Upvotes: 12
Reputation: 109237
onCreateView()
Called Every time when you change the Fragment and new Fragment become visible..
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
Upvotes: 2