实际上,我自己也做过一次。好的。
首先,将库添加到 build.gradle 文件中的依赖项中。
dependencies {
compile 'com.jpardogo.materialtabstrip:library:1.0.6'
}
这就是我的 activity_main.xml 的样子。我从支持库中添加了PagerSlidingTabStrip(通过我自己的自定义,请参阅Github repo 了解更多信息)和我的ViewPager。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame"
android:fitsSystemWindows="true" >
<include layout="@layout/toolbar" />
<com.astuetz.PagerSlidingTabStrip
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#33B5E5"
android:textColor="#FFFFFF"
app:pstsIndicatorColor="#FFFFFF"
app:pstsPaddingMiddle="true" />
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
接下来,我在我的MainActivity.java的onCreate()方法中做了以下步骤:
// Initialize the ViewPager and set an adapter
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
// Bind the tabs to the ViewPager
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
最后是FragmentPagerAdapter 类,也在MainActivity.java 中。注意Fragment getItem() 方法;这是我使用标签的位置在我的片段之间切换的地方。
class PagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Regular Tenses", "Perfect Tenses"};
public PagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
@Override
public int getCount() {
return TITLES.length;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MainFragment();
case 1:
return new PerfectFragment();
}
return null;
}
}