Android application development, often use Viewpager + Fragment, although the effect is good, but then there are some problems, the following is the initialization of the problem.
Viewpager 2 pages pre-loaded before and after initialization, even if Setoffscreenpagelimit (0) is set; It will also preload at least one page
But in a real-world scenario, we might not need this preloaded feature, and then we need to take some control of it.
The method I'm using is Setuservisiblehint (Boolean isvisibletouser)
Each time Viewpager the pre-load page, the preloaded fragment calls this method, so I'll use this method to control the data initialization in the fragment.
The premise is that the number of fragment pages is not many, set Setoffscreenpagelimit (the number of all fragment);
The reason is that if not all preloaded, then when the sliding page beyond the pre-loading range, there will be a page destroyed, then this control method is invalid, of course, if there is no special needs
Do not set this method will not have problems, mainly to see their own needs.
Here's how:
public Boolean Canexcute = true;//is only executed once for onactivitycreated in Setuservisiblehint method
public boolean Isfirstexcute = true;//flag Whether the page is loaded for the first time, in order to initialize it only once
@Override
public void onactivitycreated (Bundle savedinstancestate) {
Super.onactivitycreated (savedinstancestate);
if (Canexcute) {//page is executed on first load and not later in execution
Canexcute = false;
Setuservisiblehint (Getuservisiblehint ());
}
}
@Override
public void Setuservisiblehint (Boolean isvisibletouser) {
Super.setuservisiblehint (Isvisibletouser);
Do not allow this method to execute until the IF (Canexcute) {//onactivitycreated method executes
Return
}
if (Isvisibletouser && isfirstexcute) {//page is visible and is loaded for the first time
Isfirstexcute= false;//Tag page has been loaded once and does not need to be executed in the future
InitData ();//write the data that you only need to initialize once in this method
}
if (Getuservisiblehint ()) {//page is executed each time it is visible to the user
} else {
}
}
The above methods do not necessarily apply to all scenarios, and they need to be tested and improved when used.
Android-viewpager+fragment Initialization issues