ViewPager与Tab结合使用

咱们偶尔需要 标题页卡与ViewPager结合使用,其实原理为深简短。

然而工程中设引入android-support-design.jar

android studio中需以布局中丰富:

dependencies {     
compile fileTree(dir: 'libs', include: ['*.jar'])     
testCompile 'junit:junit:4.12'     
compile 'com.android.support:appcompat-v7:23.4.0'     
compile 'com.android.support:support-v4:23.4.0'     
compile 'com.android.support:design:23.4.0'   }
并且版本要一致,否则不能达到效果

 

首先是布局文件

<android.support.design.widget.TabLayout 
    android:id="@+id/tabs" 
    android:background="@color/search_bg_top" 
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    app:tabIndicatorColor="@color/white" 
    app:tabTextColor="@color/white" 
    app:tabSelectedTextColor="@color/bg_gray" />

 <android.support.v4.view.ViewPager 
         android:id="@+id/vp_view" 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:layout_weight="1.0" />

联网下是activity

 private List<String> mTitleList=new ArrayList();//页卡标题集合
 private View view1, view2;//页卡视图
 private List<View> mViewList = new ArrayList();//页卡视图集合
 private TabLayout mTabLayout;
 private ViewPager mViewPager;
 private LayoutInflater mInflater;



mViewPager = (ViewPager) findViewById(R.id.vp_view);
mTabLayout = (TabLayout) findViewById(R.id.tabs);

mInflater = LayoutInflater.from(this);

view1 = mInflater.inflate(R.layout.search_data, null);
view2 = mInflater.inflate(R.layout.search_vp_chart, null);

//添加页卡视图
mViewList.add(view1);
mViewList.add(view2);

//添加页卡标题
mTitleList.add("数据");
mTitleList.add("图表");

mTabLayout.setTabMode(TabLayout.MODE_FIXED);//设置tab模式,当前为系统默认模式
mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)));//添加tab选项卡
mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1)));

MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
mViewPager.setAdapter(mAdapter);//给ViewPager设置适配器
mTabLayout.setupWithViewPager(mViewPager);//将TabLayout和ViewPager关联起来。
mTabLayout.setTabsFromPagerAdapter(mAdapter);//给Tabs设置适配器

class MyPagerAdapter extends PagerAdapter {
        private List<View> mViewList;

        public MyPagerAdapter(List<View> mViewList) {
            this.mViewList = mViewList;
        }

        @Override
        public int getCount() {
            return mViewList.size();//页卡数
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;//官方推荐写法
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));//添加页卡
            return mViewList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));//删除页卡
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position);//页卡标题
        }

    }

这么十分功告成