| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
ZellaR22
8年前发布

Android Fragment延迟加载(仿微信的Viewpager-Fragment惰性加载)

   <p style="text-align:center"><img src="https://simg.open-open.com/show/ec3502e08e34291ca7d6dd79edce9ca2.gif"></p>    <p style="text-align:center">1477024003379.gif</p>    <p>我们在做应用开发的时候,一个Activity里面可能会以viewpager(或其他容器)与多个Fragment来组合使用,而如果每个fragment都需要去加载数据,或从本地加载,或从网络加载!</p>    <p>那么在这个activity刚创建的时候就变成需要初始化大量资源,请求很多接口,这样的结果,我们当然不会满意。那么,能不能做到当切换到这个fragment的时候,它才去初始化呢?</p>    <h2><strong>ok 那就如图 我们展示一下 源代码 :</strong></h2>    <p>MainActivity MyFragmentPagerAdapter</p>    <p>MoreFragment继承》LazyFragment 继承》父类BaseFragment</p>    <ul>     <li>MainActivity 这是平时 我们viewpager 配合fragment 的使用方法 我们新建工程的时候 9成都会用到此方法</li>    </ul>    <pre>  <code class="language-java">public class MainActivity extends AppCompatActivity {        @InjectView(R.id.viewPager2)      ViewPager viewPager;      private List<Fragment> fragmentList;        @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          ButterKnife.inject(this);          fragmentList = new ArrayList<>();          fragmentList.add(MoreFragment.newInstance(1,false));          fragmentList.add(MoreFragment.newInstance(2,true));          fragmentList.add(MoreFragment.newInstance(3,true));          fragmentList.add(MoreFragment.newInstance(4,true));          FragmentManager supportFragmentManager = getSupportFragmentManager();          MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(supportFragmentManager, fragmentList);          viewPager.setAdapter(myFragmentPagerAdapter);          viewPager.setOffscreenPageLimit(4);      }         class MyFragmentPagerAdapter extends FragmentPagerAdapter {          private List<Fragment> fragmentList;            public MyFragmentPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {              super(fm);              this.fragmentList = fragmentList;          }            @Override          public Fragment getItem(int position) {              return fragmentList.get(position);          }            @Override          public int getCount() {              return fragmentList.size();          }        }    }</code></pre>    <ul>     <li> <p>MoreFragment 这就是我们正常创建的fragment 和以往不同的是:</p> <p>onCreateView 方法 变成了 onCreateViewLazy</p> <p>并且 多了一个newInstance方法</p> </li>    </ul>    <pre>  <code class="language-java">public class MoreFragment extends LazyFragment {        public static final String INTENT_INT_INDEX="index";      public static MoreFragment newInstance(int tabIndex,boolean isLazyLoad) {            Bundle args = new Bundle();          args.putInt(INTENT_INT_INDEX, tabIndex);          args.putBoolean(LazyFragment.INTENT_BOOLEAN_LAZYLOAD, isLazyLoad);          MoreFragment fragment = new MoreFragment();          fragment.setArguments(args);          return fragment;      }      @Override      protected void onCreateViewLazy(Bundle savedInstanceState) {          super.onCreateViewLazy(savedInstanceState);          setContentView(R.layout.fragment_tabmain_item);        }  }</code></pre>    <ul>     <li>LazyFragment</li>    </ul>    <p>懒加载Fragment 只有创建并显示的时候才会调用onCreateViewLazy方法</p>    <ul>     <li>懒加载的原理onCreateView的时候Fragment有可能没有显示出来。</li>    </ul>    <ul>     <li> <p>但是调用到setUserVisibleHint(boolean isVisibleToUser),isVisibleToUser =</p> <p>true的时候就说明有显示出来</p> </li>     <li> <p>但是要考虑onCreateView和setUserVisibleHint的先后问题所以才有了下面的代码</p> </li>    </ul>    <p>《1》原先的Fragment的回调方法名字后面要加个Lazy,比如Fragment的onCreateView方法, 就写成onCreateViewLazy</p>    <p>《2》使用该LazyFragment会导致多一层布局深度</p>    <pre>  <code class="language-java">public class LazyFragment extends BaseFragment {      private boolean isInit = false;//真正要显示的View是否已经被初始化(正常加载)      private Bundle savedInstanceState;      public static final String INTENT_BOOLEAN_LAZYLOAD = "intent_boolean_lazyLoad";      private boolean isLazyLoad = true;      private FrameLayout layout;      private boolean isStart = false;//是否处于可见状态,in the screen        @Override      protected final void onCreateView(Bundle savedInstanceState) {          Log.d("TAG", "onCreateView() : " + "getUserVisibleHint():" + getUserVisibleHint());          super.onCreateView(savedInstanceState);          Bundle bundle = getArguments();          if (bundle != null) {              isLazyLoad = bundle.getBoolean(INTENT_BOOLEAN_LAZYLOAD, isLazyLoad);          }          //判断是否懒加载          if (isLazyLoad) {              //一旦isVisibleToUser==true即可对真正需要的显示内容进行加载              if (getUserVisibleHint() && !isInit) {                  this.savedInstanceState = savedInstanceState;                  onCreateViewLazy(savedInstanceState);                  isInit = true;              } else {                  //进行懒加载                  layout = new FrameLayout(getApplicationContext());                  layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));                  View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.fragment_lazy_loading, null);                  layout.addView(view);                  super.setContentView(layout);              }          } else {              //不需要懒加载,开门江山,调用onCreateViewLazy正常加载显示内容即可              onCreateViewLazy(savedInstanceState);              isInit = true;          }      }        @Override      public void setUserVisibleHint(boolean isVisibleToUser) {          super.setUserVisibleHint(isVisibleToUser);          Log.d("TAG", "setUserVisibleHint() called with: " + "isVisibleToUser = [" + isVisibleToUser + "]");          //一旦isVisibleToUser==true即可进行对真正需要的显示内容的加载            //可见,但还没被初始化          if (isVisibleToUser && !isInit && getContentView() != null) {              onCreateViewLazy(savedInstanceState);              isInit = true;              onResumeLazy();          }          //已经被初始化(正常加载)过了          if (isInit && getContentView() != null) {              if (isVisibleToUser) {                  isStart = true;                  onFragmentStartLazy();              } else {                  isStart = false;                  onFragmentStopLazy();              }          }      }        @Override      public void setContentView(int layoutResID) {          //判断若isLazyLoad==true,移除所有lazy view,加载真正要显示的view          if (isLazyLoad && getContentView() != null && getContentView().getParent() != null) {              layout.removeAllViews();              View view = inflater.inflate(layoutResID, layout, false);              layout.addView(view);          }          //否则,开门见山,直接加载          else {              super.setContentView(layoutResID);          }      }        @Override      public void setContentView(View view) {          //判断若isLazyLoad==true,移除所有lazy view,加载真正要显示的view          if (isLazyLoad && getContentView() != null && getContentView().getParent() != null) {              layout.removeAllViews();              layout.addView(view);          }          //否则,开门见山,直接加载          else {              super.setContentView(view);          }      }        @Deprecated      @Override      public final void onStart() {          Log.d("TAG", "onStart() : " + "getUserVisibleHint():" + getUserVisibleHint());          super.onStart();          if (isInit && !isStart && getUserVisibleHint()) {              isStart = true;              onFragmentStartLazy();          }      }        @Deprecated      @Override      public final void onStop() {          super.onStop();          Log.d("TAG", "onStop() called: " + "getUserVisibleHint():" + getUserVisibleHint());          if (isInit && isStart && getUserVisibleHint()) {              isStart = false;              onFragmentStopLazy();          }      }        //当Fragment被滑到可见的位置时,调用      protected void onFragmentStartLazy() {          Log.d("TAG", "onFragmentStartLazy() called with: " + "");      }        //当Fragment被滑到不可见的位置,offScreen时,调用      protected void onFragmentStopLazy() {          Log.d("TAG", "onFragmentStopLazy() called with: " + "");      }        protected void onCreateViewLazy(Bundle savedInstanceState) {          Log.d("TAG", "onCreateViewLazy() called with: " + "savedInstanceState = [" + savedInstanceState + "]");      }        protected void onResumeLazy() {          Log.d("TAG", "onResumeLazy() called with: " + "");      }        protected void onPauseLazy() {          Log.d("TAG", "onPauseLazy() called with: " + "");      }        protected void onDestroyViewLazy() {        }        @Override      @Deprecated      public final void onResume() {          Log.d("TAG", "onResume() : " + "getUserVisibleHint():" + getUserVisibleHint());          super.onResume();          if (isInit) {              onResumeLazy();          }      }        @Override      @Deprecated      public final void onPause() {          Log.d("TAG", "onPause() : " + "getUserVisibleHint():" + getUserVisibleHint());          super.onPause();          if (isInit) {              onPauseLazy();          }      }        @Override      @Deprecated      public final void onDestroyView() {          Log.d("TAG", "onDestroyView() : " + "getUserVisibleHint():" + getUserVisibleHint());          super.onDestroyView();          if (isInit) {              onDestroyViewLazy();          }          isInit = false;      }  }</code></pre>    <ul>     <li>BaseFragment</li>    </ul>    <pre>  <code class="language-java">public class BaseFragment extends Fragment {      protected LayoutInflater inflater;      private View contentView;      private Context context;      private ViewGroup container;        @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          context = getActivity().getApplicationContext();      }        //子类通过重写onCreateView,调用setOnContentView进行布局设置,否则contentView==null,返回null      @Override      public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {          this.inflater = inflater;          this.container = container;          onCreateView(savedInstanceState);          if (contentView == null)              return super.onCreateView(inflater, container, savedInstanceState);          return contentView;      }        protected void onCreateView(Bundle savedInstanceState) {        }        @Override      public void onDestroyView() {          super.onDestroyView();          contentView = null;          container = null;          inflater = null;      }        public Context getApplicationContext() {          return context;      }        public void setContentView(int layoutResID) {          setContentView((ViewGroup) inflater.inflate(layoutResID, container, false));      }        public void setContentView(View view) {          contentView = view;      }        public View getContentView() {          return contentView;      }        public View findViewById(int id) {          if (contentView != null)              return contentView.findViewById(id);          return null;      }        // http://stackoverflow.com/questions/15207305/getting-the-error-java-lang-illegalstateexception-activity-has-been-destroyed      @Override      public void onDetach() {          Log.d("TAG", "onDetach() : ");          super.onDetach();          try {              Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");              childFragmentManager.setAccessible(true);              childFragmentManager.set(this, null);            } catch (NoSuchFieldException e) {              throw new RuntimeException(e);          } catch (IllegalAccessException e) {              throw new RuntimeException(e);          }      }        @Override      public void onDestroy() {          Log.d("TAG", "onDestroy() : ");          super.onDestroy();      }  }</code></pre>    <p> </p>    <p> </p>    <p>来自:http://www.jianshu.com/p/8a772b9df6d5</p>    <p> </p>    
 本文由用户 ZellaR22 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1477033083443.html
ViewPager Android开发 移动开发