版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/lyhhj/article/details/48687389
最近项目中用到了滑动页面,也就是和目前市场上很火的"今日头条"页面滑动类似,在网上找了一下,大部分都是用ViewPager来实现的,刚开始我用的是ViewPager+ViewGroup,上面的标题按钮用的是HorizontalScrollView,写完之后感觉效果比较生硬,果断换掉,发现了一个效果比较好的第三方,也就是今天的主题:PagerSlidingTabStrip.好了,下面来具体介绍一下PagerSlidingTabStrip,进行一下源码解析.
一: 到GitHub上去下载源码和Demo
GitHub地址:
https://github.com/astuetz/PagerSlidingTabStrip
先看一下demo的样子吧
二:把PagerSlidingTabStrip导入我们的项目中
然后在我们的布局文件中进行声明:
<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.hankkin.PagerSlidingTabStrip"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.hankkin.PagerSlidingTabStrip.view.PagerSlidingTabStrip
android:id="@+id/tab"
app:pstsShouldExpand="false"
app:pstsUnderlineHeight="2dp"
app:pstsIndicatorHeight="2dp"
app:pstsIndicatorColor="@android:color/holo_blue_light"
app:selectedTabTextColor="@android:color/holo_blue_light"
app:pstsDividerColor="@android:color/transparent"
app:pstsTabBackground="@drawable/background"
android:background="@android:color/white"
android:layout_width="match_parent"
android:layout_height="55dp"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout></span><span style="font-size:18px;">
</span>
上面的也就是我们的标题滑动按钮,下面的ViewPager用来存放我们的内容
三:创建Adapter
<span style="font-size:14px;">package com.hankkin.PagerSlidingTabStrip.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.hankkin.PagerSlidingTabStrip.fragment.AndroidFragment;
import com.hankkin.PagerSlidingTabStrip.fragment.JavaFragment;
import com.hankkin.PagerSlidingTabStrip.fragment.ObjectCFragment;
import java.util.List;
/**
* Created by Hankkin on 15/9/20.
*/
public class MyAdapter extends FragmentPagerAdapter {
private AndroidFragment androidFragment;
private JavaFragment javaFragment;
private ObjectCFragment objectCFragment;
private String[] titles;
public MyAdapter(FragmentManager fm,String[] titles) {
super(fm);
this.titles = titles;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
if (androidFragment == null) {
androidFragment = new AndroidFragment();
}
return androidFragment;
case 1:
if (javaFragment == null) {
javaFragment = new JavaFragment();
}
return javaFragment;
case 2:
if (objectCFragment == null) {
objectCFragment = new ObjectCFragment();
}
return objectCFragment;
default:
return null;
}
}
@Override
public int getCount() {
return titles.length;
}
public String getPageTitle(int i){
return titles[i];
}
}
</span>
我这里用的是碎片Fragment,最下面的getPageTitle()是我们的PagerSlidingTabStrip中的方法,用来获取标题
接下来我们初始化PagerSlidingTabStrip和ViewPager还有我们的碎片
<span style="font-size:14px;"> private void initViews(){
fragments = new ArrayList<>();
pagerTab = (PagerSlidingTabStrip) findViewById(R.id.tab);
pager = (ViewPager) findViewById(R.id.pager);
for (int i=0;i<titles.length;i++){
Fragment fragment = new Fragment();
fragments.add(fragment);
}
adapter = new MyAdapter(getSupportFragmentManager(),titles);
pager.setAdapter(adapter);
pagerTab.setViewPager(pager);
}</span>
在Adapter中利用碎片管理器获取我们的碎片和标题相对应上.这里面需要注意提一下,如果碎片的个数比较少我们可以手动创建碎片,如果像今日头条很多的话也没关系,动态创建Fragment,因为我们可以看到头条的每个碎片中的内容都是类似的,所以说动态创建也未尝不可,只有个别特殊的我们也可以特殊处理.
就这么简单就可以实现类似头条的页面滑动效果,下面我们来看一下PagerSlidingTabStrip的源码吧,看懂了之后也方便我们进行改进.
四:PagerSlidingTabStrip源码解析
首先我们看几个比较重要的属性
private int indicatorColor = 0xFF666666;// 滑动指示器颜色
private int underlineColor = 0x1A000000;//在视图的底部的全宽度的线pstsunderlinecolor颜色
private int dividerColor = 0x1A000000;//选项卡之间的分隔pstsdividercolor颜色
private boolean shouldExpand = false;//pstsshouldexpand如果设置为TRUE,每个标签都给予同样的重量,默认为false
private boolean textAllCaps = true;//pststextallcaps如果为真,所有选项卡标题都是大写,默认为true
private int scrollOffset = 52;//pstsscrolloffset卷轴被选择的标签的偏移
private int indicatorHeight = 8;//滑动指示器pstsindicatorheight
private int underlineHeight = 2;//在视图的底部的全宽度的线pstsunderlineheight高度
private int dividerPadding = 12;//pstsdividerpadding顶部和底部填充的分频器
private int tabPadding = 24;//pststabpaddingleftright左、右填充每个选项卡
private int dividerWidth = 1;//选项卡分割线宽度
private int tabTextSize = 12;//选项卡字体大小
private int tabTextColor = 0xFF666666;//选项卡字体颜色
private int selectedTabTextColor = 0xFF666666;//当前选中字体颜色
private Typeface tabTypeface = null;
private int tabTypefaceStyle = Typeface.NORMAL;
private int lastScrollX = 0;
private int tabBackgroundResId = R.drawable.background;//pststabbackground背景绘制的每个标签,应该是一个statelistdrawable
我们可以自己定义这些属性的值,因为可能默认的不太好看1.首先看一下我们的构造会初始化一些什么属性
<span style="font-size:14px;">public PagerSlidingTabStrip(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFillViewport(true);//默认使子view可以拉伸来填满整个屏幕
setWillNotDraw(false);//默认不执行OnDraw()方法
//初始化盛放按钮标题的线性布局
tabsContainer = new LinearLayout(context);
tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
addView(tabsContainer);
DisplayMetrics dm = getResources().getDisplayMetrics();
//导入相应资源文件
scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);
tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);
// get system attrs (android:textSize and android:textColor)
TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
tabTextSize = a.getDimensionPixelSize(0, tabTextSize);
tabTextColor = a.getColor(1, tabTextColor);
a.recycle();
// get custom attrs
a = context.obtainStyledAttributes(attrs, R.styleable.PagerSlidingTabStrip);
indicatorColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsIndicatorColor, indicatorColor);
//tab文字选中时的颜色,默认和滑动指示器的颜色一致
selectedTabTextColor=a.getColor(R.styleable.PagerSlidingTabStrip_selectedTabTextColor, indicatorColor);
//初始化属性样式
underlineColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsUnderlineColor, underlineColor);
dividerColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsDividerColor, dividerColor);
indicatorHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsIndicatorHeight, indicatorHeight);
underlineHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsUnderlineHeight, underlineHeight);
dividerPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsDividerPadding, dividerPadding);
tabPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsTabPaddingLeftRight, tabPadding);
tabBackgroundResId = a.getResourceId(R.styleable.PagerSlidingTabStrip_pstsTabBackground, tabBackgroundResId);
shouldExpand = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsShouldExpand, shouldExpand);
scrollOffset = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsScrollOffset, scrollOffset);
textAllCaps = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsTextAllCaps, textAllCaps);
a.recycle();
rectPaint = new Paint();
rectPaint.setAntiAlias(true);
rectPaint.setStyle(Style.FILL);
dividerPaint = new Paint();
dividerPaint.setAntiAlias(true);
dividerPaint.setStrokeWidth(dividerWidth);
defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f);
if (locale == null) {
locale = getResources().getConfiguration().locale;
}
}</span>
这些基本都能看懂,主要都是初始化一些属性,代码中也有相应的注释,就不一一介绍了
2.定义ViewPager滑动监听器,设置当前pager的位置
<span style="font-size:14px;">private class PageListener implements OnPageChangeListener {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
currentPosition = position;
currentPositionOffset = positionOffset;
scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth()));
invalidate();
if (delegatePageListener != null) {
delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
scrollToChild(pager.getCurrentItem(), 0);
}
if (delegatePageListener != null) {
delegatePageListener.onPageScrollStateChanged(state);
}
}
@Override
public void onPageSelected(int position) {
selectedPosition = position;
updateTabStyles();
if (delegatePageListener != null) {
delegatePageListener.onPageSelected(position);
}
}
}</span>
3.更新标题样式,也就是滑动到当前标题下设置标题状态
<span style="font-size:14px;">private void updateTabStyles() {
for (int i = 0; i < tabCount; i++) {
View v = tabsContainer.getChildAt(i);
v.setBackgroundResource(tabBackgroundResId);
if (v instanceof TextView) {
TextView tab = (TextView) v;
tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);
tab.setTypeface(tabTypeface, tabTypefaceStyle);
tab.setTextColor(tabTextColor);
// setAllCaps() is only available from API 14, so the upper case is made manually if we are on a
// pre-ICS-build
if (textAllCaps) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
tab.setAllCaps(true);
} else {
tab.setText(tab.getText().toString().toUpperCase(locale));
}
}
if (i == selectedPosition) {
tab.setTextColor(selectedTabTextColor);
}
}
}
}</span>
大体就差不多这些了,好了,给大家看一下我自己完善后的样子吧
没有做太多调整,只是稍微的改了一下样式,里面还有一些比较细节的东西没有介绍,比如标题的宽度是平均分配还是分体字体长度进行设置,我们可以修改shouldExpand属性
大家有兴趣的自己仔细研究一下吧.