一个标准的TabLayout+ViewPager+Fragment

一个标准的TabLayout+ViewPager+Fragment

首先引入一个依赖:

    compile 'com.android.support:design:25.0.0'

1.XML

    
    

        

        

        
        
        
    

为了保证滑动的流畅,这里使用了CoordinatorLayout作为最外部的容器

2.Java

    @Bind(R.id.tl_home)
    TabLayout tlHome;
    @Bind(R.id.vp_home)
    ViewPager vpHome;
    
    String[] TITLE={"LineChart","BarChart"};
    tlHome.setupWithViewPager(vpHome);
        
    List fragmentList = new ArrayList();
        
    fragmentList.add(new ChartFragment());
    
    MyPagerAdapter adapter = newMyPagerAdapter(getSupportFragmentManager(), fragmentList, TITLE);
    
    vpHome.setAdapter(adapter);
    
    //实例化TabPageIndicator然后设置ViewPager与之关联
    tlHome.setupWithViewPager(vpHome);
    
    //如果我们要对ViewPager设置监听,用indicator设置就行了
    tlHome.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            vpHome.setCurrentItem(tab.getPosition());
        }
        @Override
            public void onTabUnselected(TabLayout.Tab tab) {
        }
        @Override
            public void onTabReselected(TabLayout.Tab tab) {
        }
    });

你可能感兴趣的:(一个标准的TabLayout+ViewPager+Fragment)