1.第三方使用先加入依赖在build.gradle
dependencies {
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
}
2.在layout里加入PagerSlidingTabStrip控件,它通常要==在ViewPager控件之上==
<com.astuetz.PagerSlidingTabStrip
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v4.view.ViewPager>
3.在你的onCreate方法(或者onCreateView对于一个fragment),绑定PagerSlidingTabStrip控件到ViewPager上
// 初始化ViewPager并且添加适配器
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new TestAdapter(getSupportFragmentManager()));
//向ViewPager绑定PagerSlidingTabStrip
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
4.(可选的)如果你想在你的ViewPager用到onPageChangeListener监听方法,你应该如下设置,而不是直接用ViewPager设置
// 从上面继续
tabs.setOnPageChangeListener(mPageChangeListener);
个性化设置
pstsIndicatorColor 滑动条的颜色
pstsUnderlineColor 滑动条所在的那个全宽线的颜色
pstsDividerColor 每个标签的分割线的颜色
pstsIndicator 滑动条的高度
pstsUnderlineHeight Height 滑动条所在的那个全宽线的高度
pstsDividerPadding 分割线底部和顶部的填充宽度
pstsTabPaddingLeftRight 每个标签左右填充宽度
pstsScrollOffset
pstsTabBackground 每个标签的背景,应该是一个StateListDrawable
pstsShouldExpand 如果设置为true,每个标签是相同的控件,均匀平分整个屏幕,默认是false
pstsTextAllCaps 如果为true,所有标签都是大写字母,默认为true
代码块:
public class MainActivity extends AppCompatActivity {
String [] arr ={"页面一","页面二","页面三","页面二","页面三"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ViewPager vp= (ViewPager) findViewById(R.id.vp);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
vp.setAdapter(new MyAdapter(getSupportFragmentManager()));
//标题和viewpager进行关联
tabs.setViewPager(vp);
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
*
* @param position 添加横向滑动的方法
* @return
*/
@Override
public CharSequence getPageTitle(int position) {
return arr[position];
}
@Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch (position){
case 0:
fragment = new com.bwei.horicalscrollview.Fragment();
break;
case 1:
fragment = new Fragment1();
break;
case 2:
fragment = new Fragment2();
break;
case 3:
fragment = new Fragment2();
break;
case 4:
fragment = new Fragment2();
break;
case 5:
fragment = new Fragment2();
break;
}
return fragment;
}
@Override
public int getCount() {
return 5;
}
}
}