最近项目中用到了滑动页面,也就是和目前市场上很火的"今日头条"页面滑动类似,在网上找了一下,大部分都是用ViewPager来实现的,刚开始我用的是ViewPager+ViewGroup,上面的标题按钮用的是HorizontalScrollView,写完之后感觉效果比较生硬,果断换掉,发现了一个效果比较好的第三方,也就是今天的主题:PagerSlidingTabStrip.好了,下面来具体介绍一下PagerSlidingTabStrip,进行一下源码解析.

一:到GitHub上去下载源码和Demo


Android Studio仿今日头条 android开发今日头条的源码_ide

Android Studio仿今日头条 android开发今日头条的源码_android_02

二:把PagerSlidingTabStrip导入我们的项目中

然后在我们的布局文件中进行声明:

<?xml version="1.0" encoding="utf-8"?>上面的也就是我们的标题滑动按钮,下面的ViewPager用来存放我们的内容

三:创建Adapter

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 2021年06月02日/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]; }}我这里用的是碎片Fragment,最下面的getPageTitle()是我们的PagerSlidingTabStrip中的方法,用来获取标题

接下来我们初始化PagerSlidingTabStrip和ViewPager还有我们的碎片

private void initViews(){ fragments = new ArrayList<>(); pagerTab = (PagerSlidingTabStrip) findViewById(R.id.tab); pager = (ViewPager) findViewById(R.id.pager); for (int i=0;i

在Adapter中利用碎片管理器获取我们的碎片和标题相对应上.这里面需要注意提一下,如果碎片的个数比较少我们可以手动创建碎片,如果像今日头条很多的话也没关系,动态创建Fragment,因为我们可以看到头条的每个碎片中的内容都是类似的,所以说动态创建也未尝不可,只有个别特殊的我们也可以特殊处理.

就这么简单就可以实现类似头条的页面滑动效果,下面我们来看一下PagerSlidingTabStrip的源码吧,看懂了之后也方便我们进行改进.

四:PagerSlidingTabStrip源码解析

首先我们看几个比较重要的属性

private int indicatorColor = 0xFF666666;//滑动指示器颜色private int underlineColor = 0x1A000000;//在视图的底部的全宽度的线pstsunderlinecolor颜色private int dividerColor = 0x1A000000;//选项卡之间的分隔pstsdividercolor颜色private boolean shouldExpand = false;//pstsshouldexpand如果设置为TRUE,每个标签都给予同样的重量,默认为falseprivate boolean textAllCaps = true;//pststextallcaps如果为真,所有选项卡标题都是大写,默认为trueprivate int scrollOffset = 52;//pstsscrolloffset卷轴被选择的标签的偏移private int indicatorHeight = 8;//滑动指示器pstsindicatorheightprivate 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.首先看一下我们的构造会初始化一些什么属性

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 attrsa = 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;}}这些基本都能看懂,主要都是初始化一些属性,代码中也有相应的注释,就不一一介绍了

2.定义ViewPager滑动监听器,设置当前pager的位置

private class PageListener implements OnPageChangeListener {@Overridepublic 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);}}@Overridepublic void onPageScrollStateChanged(int state) {if (state == ViewPager.SCROLL_STATE_IDLE) {scrollToChild(pager.getCurrentItem(), 0);}if (delegatePageListener != null) {delegatePageListener.onPageScrollStateChanged(state);}}@Overridepublic void onPageSelected(int position) {selectedPosition = position;updateTabStyles();if (delegatePageListener != null) {delegatePageListener.onPageSelected(position);}}}3.更新标题样式,也就是滑动到当前标题下设置标题状态
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-buildif (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);}}}}大体就差不多这些了,好了,给大家看一下我自己完善后的样子吧

Android Studio仿今日头条 android开发今日头条的源码_Android Studio仿今日头条_03

没有做太多调整,只是稍微的改了一下样式,里面还有一些比较细节的东西没有介绍,比如标题的宽度是平均分配还是分体字体长度进行设置,我们可以修改shouldExpand属性

大家有兴趣的自己仔细研究一下吧.