一個標(biāo)準(zhǔn)的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然后設(shè)置ViewPager與之關(guān)聯(lián)
tlHome.setupWithViewPager(vpHome);
//如果我們要對ViewPager設(shè)置監(jiān)聽润歉,用indicator設(shè)置就行了
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) {
}
});