Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code right after a fragment becomes visible for the first time

I have a fragment which shows a line chart created with MPAndroidChart. Loading the fragment takes about 200 milliseconds.

I want to improve the perceived app performance by loading the chart data data right after the fragment becomes visible.

Therefore I need to execute code right after the fragment becomes visible, but only the FIRST time it becomes visible.

I can not use onResume(), since it gets called just before the fragment is visible.

Note: I can not use an asynchrounous task, it needs to be done on the UI-thread.

like image 834
Mike76 Avatar asked Sep 03 '15 14:09

Mike76


People also ask

Which method is called once fragment is visible?

onCreateView() : Inflate the XML layout for the Fragment in this callback. The system calls this method to draw the Fragment UI for the first time. As a result, the Fragment is visible in the Activity .

How do you know when a fragment becomes visible?

fragment:fragment:1.1. 0 you can just use onPause and onResume callbacks to determine which fragment is currently visible for the user. onResume callback is called when fragment became visible and onPause when it stops to be visible.

What callback method is invoked by first the system during an fragment life cycle?

The onAttach() callback is invoked when the fragment has been added to a FragmentManager and is attached to its host activity. At this point, the fragment is active, and the FragmentManager is managing its lifecycle state.


1 Answers

define and override

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

}

then put in onCreateView() function these two lines

      setUserVisibleHint(false);
      setUserVisibleHint(true);

then put the code you wanted to be done at fragment start in onStart() function

@Override
public void onStart() {
    super.onStart();
     //your initial code is here.
}
like image 197
Muhammad Rabieh Avatar answered Oct 11 '22 05:10

Muhammad Rabieh