美文网首页
ViewPager+Fragment懒加载

ViewPager+Fragment懒加载

作者: 遇见初夏 | 来源:发表于2019-01-14 17:11 被阅读0次

    关于fragment懒加载文章,网上有很多,大家可根据自己项目的情况来选择,在此总结一下我在项目中用到的方法。

    为什么使用fragment懒加载?

    ViewPager默认加载当前页面,而且预加载当前页面的前后两个页面数据(即同时会加载3个页面的数据),如果3个页面都有网络请求,就会影响性能,影响用户体验,由此,懒加载就尤为重要了,可以在滑到哪个fragment的时候,该fragment再进行网络请求。

    直接上代码:
    第1步:创建BaseFragment

    public abstract class BaseFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(setContentView(), container, false);
            findViewById(rootView);
            return rootView;
        }
        /*
         * 初始化布局:
         *      findViewById() 或者 ButterKnife.bind(this, view);
         * @param rootView 布局UI
         */
        protected abstract void findViewById(View rootView);
        /*
         * 记载布局文件:
         *      R.layout.xxx
         */
        protected abstract int setContentView();
    }
    

    第2步:创建LazyBaseFragment 继承BaseFragment

    public abstract class LazyBaseFragment extends BaseFragment {
        /**
         * 是否初始化布局
         */
        protected boolean isViewInitiated;
        /**
         * 当前界面是否可见
         */
        protected boolean isVisibleToUser;
    
        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            isViewInitiated = true;
            isCanLoadData();
        }
    
        @Override
        public void setUserVisibleHint(boolean isVisibleToUser) {
            super.setUserVisibleHint(isVisibleToUser);
            // 是否对用户可见
            this.isVisibleToUser = isVisibleToUser;
            if (isVisibleToUser) {
                isCanLoadData();
            }
        }
    
        /*
         * 执行数据加载: 条件是view初始化完成并且对用户可见
         */
        private void isCanLoadData() {
            if (isViewInitiated && isVisibleToUser) {
                lazyLoad();
                // 加载过数据后,将isViewInitiated和isVisibleToUser设置成false,防止重复加载数据
                isViewInitiated = false;
                isVisibleToUser = false;
            }
        }
        protected abstract void lazyLoad();
    }
    

    第3步:创建FragmentOne、FragmentTwo,FragmentThree三个类继承LazyBaseFragment,下面以FragmentOne为例;

    public class FragmentOne extends LazyBaseFragment {
        private static final String TAG = "lazy";
        private Context context;
        
        ***此处省略其他方法***
    
        @Override
        protected void findViewById(View rootView) {
            TextView tv = (TextView) rootView.findViewById(R.id.id_fragment_content);
            tv.setText("fragment 1");
        }
    
        @Override
        protected int setContentView() {
            return R.layout.fragment_item;
        }
    
        @Override
        protected void lazyLoad() {
            //此处模拟网络请求过程
            Log.e(TAG, "fragment 1 开始加载数据。。。");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.e(TAG, "fragment 1 数据加载完成!");
                }
            }, 3000);
        }
    }
    

    第4步:创建fragment_item.xml,就一个TextView。

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/id_fragment_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </android.support.constraint.ConstraintLayout>
    

    第5步:接下来就是创建主页面了,先创建activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <android.support.v4.view.ViewPager
            android:id="@+id/id_viewpager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
        <android.support.design.widget.BottomNavigationView
            android:id="@+id/id_bottom_menu"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="#fff"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/navigation" />
    </android.support.constraint.ConstraintLayout>
    

    navigation.xml

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:id="@+id/navigation_f1"
            android:title="F1" />
        <item
            android:id="@+id/navigation_f2"
            android:title="F2" />
        <item
            android:id="@+id/navigation_f3"
            android:title="F3" />
    </menu>
    

    然后是MainActivity.java

    public class MainActivity extends AppCompatActivity {
        ViewPager idViewPager;
        BottomNavigationView idBottomMenu;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            idBottomMenu = (BottomNavigationView) findViewById(R.id.id_bottom_menu);
            idBottomMenu.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
    
                @Override
                public boolean onNavigationItemSelected(MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.navigation_f1:
                            idViewPager.setCurrentItem(0);
                            return true;
                        case R.id.navigation_f2:
                            idViewPager.setCurrentItem(1);
                            return true;
                        case R.id.navigation_f3:
                            idViewPager.setCurrentItem(2);
                            return true;
                    }
                    return false;
                }
            });
    
            idViewPager = (ViewPager) findViewById(R.id.id_viewpager);
            idViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    
                }
    
                @Override
                public void onPageSelected(int position) {
                    idBottomMenu.getMenu().getItem(position).setChecked(true);
                }
    
                @Override
                public void onPageScrollStateChanged(int state) {
    
                }
            });
            MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
            adapter.addFragment(new FragmentOne());
            adapter.addFragment(new FragmentTwo());
            adapter.addFragment(new FragmentThree());
            idViewPager.setAdapter(adapter);
            //要设置viewpager的limit为2,因为滑动到fragment3的时候,fragment3的左侧有2个页面了
            idViewPager.setOffscreenPageLimit(2);
        }
    
        //这里自定义的adapter要继承FragmentPagerAdapter
        class MyAdapter extends FragmentPagerAdapter {
            private List<Fragment> fragments = new ArrayList<>();
    
            public MyAdapter(FragmentManager fm) {
                super(fm);
            }
    
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }
    
            @Override
            public int getCount() {
                return fragments.size();
            }
    
            public void addFragment(Fragment fragment) {
                fragments.add(fragment);
            }
        }
    }
    

    关于FragmentPagerAdapter和FragmentStatePagerAdapter区别

    相关文章

      网友评论

          本文标题:ViewPager+Fragment懒加载

          本文链接:https://www.haomeiwen.com/subject/nzqjdqtx.html