一个标准的TabLayout+ViewPager+Fragment
首先引入一个依赖:
compile 'com.android.support:design:25.0.0'
1.XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/content_ma in"
android:layout_width="match _parent"
android:layout_height="matc h_parent"
app:layout_behavior="@strin g/appbar_scrolling_view_beh avior"
tools:context="skkk.cleanwa terinformation.MainActivity "
tools:showIn="@layout/app_bar_main">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:background="@color/colorPrimary"
android:id="@id/tl_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="center"
app:tabMode="scrollable"
app:tabTextColor="@color/colorWhite"
app:tabSelectedTextColor="@color/colorLightBlue"
app:tabIndicatorColor="@color/colorAccent"
/>
<android.support.v4.view.ViewPager
android:id="@id/vp_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
为了保证滑动的流畅,这里使用了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<Fragment> fragmentList = new ArrayList<Fragment>();
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) {
}
});