Lennie
Lennie

Reputation: 2069

Fragment become visible

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:

  1. onStart
  2. onResume
  3. onAttach

But my code doesn't fire everytime.

Am using the Android v4 comp lib with SherlockFragment as my base class.

Upvotes: 4

Views: 9585

Answers (5)

Lieuwe
Lieuwe

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

Sanjay Bhalani
Sanjay Bhalani

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

Carlo Chum
Carlo Chum

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

user123
user123

Reputation: 538

You can use

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

Have a look at this

Upvotes: 12

user370305
user370305

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

Related Questions