美文网首页
Android首页经典导航

Android首页经典导航

作者: 狂奔的_土豆 | 来源:发表于2020-04-20 15:17 被阅读0次
    image.png

    采用Viewpager+Fragment实现

    import android.support.annotation.NonNull;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.view.ViewGroup;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class FragmentAdapter<F extends Fragment> extends FragmentPagerAdapter {
        
        private final List<F> mFragmentSet = new ArrayList<>();
        
        private F mCurrentFragment;
        
        private ViewPager mViewPager;
    
        public BaseFragmentAdapter(FragmentManager fm) {
            super(fm);
        }
    
        @SuppressWarnings("unchecked")
        @Override
        public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            if (getCurrentFragment() != object) {
                // 记录当前的Fragment对象
                mCurrentFragment = (F) object;
            }
            super.setPrimaryItem(container, position, object);
        }
    
        public void addFragment(F fragment) {
            mFragmentSet.add(fragment);
        }
       
        @Override
        public void startUpdate(@NonNull ViewGroup container) {
            super.startUpdate(container);
            if (container instanceof ViewPager) {
                // 记录绑定 ViewPager
                mViewPager = (ViewPager) container;
            }
        }
    
        public void setCurrentItem(int position) {
            if (mViewPager != null) {
                mViewPager.setCurrentItem(position);
            }
        }
    
        public void setCurrentItem(int position, boolean smoothScroll) {
            if (mViewPager != null) {
                mViewPager.setCurrentItem(position, smoothScroll);
            }
        }
    
        ------------------- 此处更多代码略 -------------------
    
    }
    
    
    BaseFragmentAdapter mPagerAdapter = new BaseFragmentAdapter<>(getSupportFragmentManager());
    mPagerAdapter.addFragment(new FragmentA());
    mPagerAdapter.addFragment(new FragmentB());
    mPagerAdapter.addFragment(new FragmentC());
    mPagerAdapter.addFragment(new FragmentD());
    
    ViewPager mViewPager ;
    mViewPager .setAdapter(mPagerAdapter);
    // 限制页面数量
    mViewPager .setOffscreenPageLimit(mPagerAdapter.getCount());
    

    相关文章

      网友评论

          本文标题:Android首页经典导航

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