When we do application development, an activity may be combined with viewpager (or other containers) with multiple fragment, and if each fragment needs to load data, load it locally, or load it from the network, Then it becomes necessary to initialize a lot of resources when the activity is just created. Such a result, of course we will not be satisfied. So, can you do it when you switch to this fragment and it initializes?
The answer lies in the Setuservisiblehint method in fragment.
import android.support.v4.app.fragment;/** * @Title: Basefragment.java * @ Package com.ibanglife.fragment * @Description: TODO Blog: http://www.cnblogs.com/brantliu/* @author Brant Liu [email Protected] * @date 2015-11-2 PM 2:56:22 * @version V1.0 */public abstract class Basefragment extends fragment{protected b Oolean isvisible;/** * Here implements the slow load of fragment data. * @param isvisibletouser */@Overridepublic void Setuservisiblehint (Boolean isvisibletouser) {Super.setuservisiblehint (Isvisibletouser); if (Getuservisiblehint ()) {isVisible = true; Onvisible (); } else {isVisible = false; Oninvisible (); }}protected void Onvisible () {lazyload (); } protected abstract void Lazyload (); protected void Oninvisible () {}}
In Basefragment, I added three methods, one is onvisiable, which is called when fragment is set to visible, one is oninvisible, that is, fragment is set to not be visible when called. In addition, a Lazyload abstract method is written, which is called in the onvisible. You might think, why not just call it in Getuservisiblehint?
This is written for reuse of code. Because in fragment, we also need to create a view (the Oncreateview () method), and may need to do other small amounts of initialization when it is not visible (such as initializing a remote service that needs to be called through Aidl), and so on. And Setuservisiblehint is called before Oncreateview, then when the view is not initialized, in the lazyload of the use, there will be a null pointer exception. And by pulling the lazyload out into a method, its subclasses can do this:
public class Contentfragment extends basefragment{ //Flag bit, the flag has been initialized to complete. private Boolean isprepared; @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {view View = Inflater.inflate (R.layout.fragment_open_result, container, false); XXX Initializes the view's controls isprepared = true; Lazyload (); return view; } @Override protected void Lazyload () { if (!isprepared | |!isvisible) { return; } Populate the data for each control }}
Android-fragment correct use method Introduction, Setuservisiblehint Method realization Data Lazy load