I want to add some proper navigation to my app. I have two fragments and I want to make a title strip tabs (similar to the one in Play Newsstand or the Play Store with material design) that switches between the two fragments. I don't have a very good understanding of the ViewPager
or PagerAdapter
. I'm also trying to use this library. I don't know where to get started. Thanks in advance.
9762 次
2 回答
7
实际上,我自己曾经做过一次。好的。
首先,将库添加到build.gradle文件中的依赖项中。
dependencies {
compile 'com.jpardogo.materialtabstrip:library:1.0.6'
}
这就是我的activity_main.xml的样子。我从支持库中添加了PagerSlidingTabStrip
(使用我自己的自定义,请参阅Github 存储库了解更多信息)和我的。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.javaonCreate()
的方法中执行了以下步骤:
// 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;
}
}
于 2014-11-27T00:07:42.833 回答