The fragment becomes visible.

Every time my fragment becomes visible to the user, I want to execute a world of code that calls a web service, extracts some data and displays it on the screen. I got part of a web service, etc., but not sure which event I should add my code to .... I tried:

  • Onstart
  • onResume
  • onAttach

But my code does not work every time.

I am using Android v4 comp lib with SherlockFragment as a base class.

+4
source share
5 answers

onResume() is called every time your fragment becomes visible to the user. Something is wrong with your code if it is not

onCreateView() is called first when the fragment needs to draw its user interface

Update . This accepted answer worked 5 years ago - it no longer works

-17
source

you can use

 @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { } else { } } 

Take a look

+12
source

It may be very old, but I found that setUserVisibleHint () does not work for many of my use cases. Instead, I had to resort to a hacker using ViewTreeObserver.

Basically, after your fragment is initialized, you will get a view inside it and follow these steps:

 myViewInFragment.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { myMethodWhenFragmentFirstBecomesVisible(); myViewInFragment.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); } 
+3
source

onCreateView()

Called every time you change a fragment and a new fragment becomes visible.

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
+2
source

The following method is used to determine when the Fragment becomes visible to the 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; } }} 
0
source

All Articles