Android应用中仿今日头条App制作ViewPager指示器
一、概述
顶部ViewPager指示器的字体变色,该效果图是这样的:
大概是今天头条的app,神奇的地方就在于,切换ViewPager页面的时候,顶部指示器改成了字体颜色的变化,个人觉得还是不错的。
那么核心的地方就是做一个支持字体这样逐渐染色就可以了,我大概想了32s,扫描了一些可能实现的方案,最终定位了一个靠谱的,下面我就带大家开始实现的征程。
实现之前贴一下我们的效果图:
1、简单使用
效果如上图了,关于颜失色的改变我添加了两个方向,一个是左方向,一个是有方向。
单纯的使用,可能觉得没什么意思,下面看结合ViewPager使用的一个例子。
2、结合ViewPager使用
可以看到我们切换页面的时候,上面的指示器的效果,棒棒哒~~~
当然了,学会了原理,你可以扩展,可以做个性的进度条,可以将字体变色改为背景色变色,可以把方向改为上下,太多了,自己去抠脚想把。
二、原理
看完效果图,有木有什么思路~~~花几分钟想想,因为原理很简单~~
我大致想了下,目测绘制半个字估计不行,那么就在绘制范围上下功夫,你可以全部绘制,但是我控制显示的范围,所以上述效果:
其实是绘制了两遍字体,但是呢,分别控制了绘制的显示范围,实现了逐渐变色的效果,那么对于范围的控制,有什么方便的API么,显然是有的
canvas有个clipRect的方法~~~ok,原理分析完毕~~
三、实现
说到实现,那第一步肯定又是自定义属性,我们这里的属性,需要text,textSize,textOriginColor,textChangeColor,progress,大致看一下,应该都能看出来作用吧,看不出来没事,结合下面的代码。tip:我们的View叫做ColorTrackView,感谢小七的命名。
1、自定义属性和获取
attr.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="text" format="string" /> <attr name="text_size" format="dimension" /> <attr name="text_origin_color" format="color|reference" /> <attr name="text_change_color" format="color|reference" /> <attr name="progress" format="float" /> <attr name="direction"> <enum name="left" value="0" /> <enum name="right" value="1" /> </attr> <declare-styleable name="ColorTrackView"> <attr name="text" /> <attr name="text_size" /> <attr name="text_origin_color" /> <attr name="text_change_color" /> <attr name="progress" /> <attr name="direction" /> </declare-styleable> </resources>
然后在我们的ColorTrackView的构造方法中进行获取这些个渣渣属性:
public class ColorTrackView extends View { private int mTextStartX; public enum Direction { LEFT , RIGHT ; } private int mDirection = DIRECTION_LEFT; private static final int DIRECTION_LEFT = 0 ; private static final int DIRECTION_RIGHT= 1 ; public void setDirection(int direction) { mDirection = direction; } private String mText = "张鸿洋"; private Paint mPaint; private int mTextSize = sp2px(30); private int mTextOriginColor = 0xff000000; private int mTextChangeColor = 0xffff0000; private Rect mTextBound = new Rect(); private int mTextWidth; private int mRealWidth; private float mProgress; public ColorTrackView(Context context) { super(context, null); } public ColorTrackView(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ColorTrackView); mText = ta.getString(R.styleable.ColorTrackView_text); mTextSize = ta.getDimensionPixelSize( R.styleable.ColorTrackView_text_size, mTextSize); mTextOriginColor = ta.getColor( R.styleable.ColorTrackView_text_origin_color, mTextOriginColor); mTextChangeColor = ta.getColor( R.styleable.ColorTrackView_text_change_color, mTextChangeColor); mProgress = ta.getFloat(R.styleable.ColorTrackView_progress, 0); mDirection = ta.getInt(R.styleable.ColorTrackView_direction, mDirection); ta.recycle(); mPaint.setTextSize(mTextSize); measureText(); } private void measureText() { mTextWidth = (int) mPaint.measureText(mText); mPaint.getTextBounds(mText, 0, mText.length(), mTextBound); }
可以看到我同时贴出了成员变量,大家简单看下就行了,都比较简单。
获取了属性,初始化完成一些成员变量以后,那么应该走向我们的measure之旅了~~
2、onMeasure
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = measureWidth(widthMeasureSpec); int height = measureHeight(heightMeasureSpec); setMeasuredDimension(width, height); mRealWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight(); mTextStartX = mRealWidth / 2 - mTextWidth / 2; } private int measureHeight(int measureSpec) { int mode = MeasureSpec.getMode(measureSpec); int val = MeasureSpec.getSize(measureSpec); int result = 0; switch (mode) { case MeasureSpec.EXACTLY: result = val; break; case MeasureSpec.AT_MOST: case MeasureSpec.UNSPECIFIED: result = mTextBound.height(); break; } result = mode == MeasureSpec.AT_MOST ? Math.min(result, val) : result; return result + getPaddingTop() + getPaddingBottom(); } private int measureWidth(int measureSpec) { int mode = MeasureSpec.getMode(measureSpec); int val = MeasureSpec.getSize(measureSpec); int result = 0; switch (mode) { case MeasureSpec.EXACTLY: result = val; break; case MeasureSpec.AT_MOST: case MeasureSpec.UNSPECIFIED: // result = mTextBound.width(); result = mTextWidth; break; } result = mode == MeasureSpec.AT_MOST ? Math.min(result, val) : result; return result + getPaddingLeft() + getPaddingRight(); }
关于测量,也是比较传统的写法,根据传入的widthMeasureSpec、heightMeasureSpec,利用MeasureSpec分别获取模式和值,如何是EXACTLY万事大吉,如果是AT_MOST、UNSPECIFIED那么就进行自己测量需要的空间,当然了,最好注意如果是AT_MOST不应该大于父类传入的值。
这里提一下,如果偷懒的话,可以选择继承TextView,然后测量就不需要写了,TextView默认帮你实现了,还能利用TextView的一些属性,不过咱们这个例子比较简单,我最终还是选择了继承View,继承View有种everything under control 的感觉。
测量完成以后,不用说都是绘制了。
3、onDraw
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int r = (int) (mProgress* mTextWidth +mTextStartX ); if(mDirection == DIRECTION_LEFT) { drawChangeLeft(canvas, r); drawOriginLeft(canvas, r); }else { drawOriginRight(canvas, r); drawChangeRight(canvas, r); } } private void drawChangeRight(Canvas canvas, int r) { drawText(canvas, mTextChangeColor, (int) (mTextStartX +(1-mProgress)*mTextWidth), mTextStartX+mTextWidth ); } private void drawOriginRight(Canvas canvas, int r) { drawText(canvas, mTextOriginColor, mTextStartX, (int) (mTextStartX +(1-mProgress)*mTextWidth) ); } private void drawChangeLeft(Canvas canvas, int r) { drawText(canvas, mTextChangeColor, mTextStartX, (int) (mTextStartX + mProgress * mTextWidth) ); } private void drawOriginLeft(Canvas canvas, int r) { drawText(canvas, mTextOriginColor, (int) (mTextStartX + mProgress * mTextWidth), mTextStartX +mTextWidth ); } private void drawText(Canvas canvas , int color , int startX , int endX) { mPaint.setColor(color); canvas.save(Canvas.CLIP_SAVE_FLAG); canvas.clipRect(startX, 0, endX, getMeasuredHeight()); canvas.drawText(mText, mTextStartX, getMeasuredHeight() / 2 + mTextBound.height() / 2, mPaint); canvas.restore(); }
绘制的核心就在于利用mProgress和方向去计算应该clip的范围,具体的参考代码,没什么难点。有了范围以后,无非就是drawText~~~这里只讲主要代码。
主要的方法介绍完毕,我们就该测试了。
四、测试
1、简单测试
布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:zhy="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" > <com.zhy.view.ColorTrackView android:id="@+id/id_changeTextColorView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="#44ff0000" android:padding="10dp" zhy:progress="0" zhy:text="张鸿洋" zhy:text_change_color="#ffff0000" zhy:text_origin_color="#ff000000" zhy:text_size="60sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:gravity="center" android:orientation="horizontal" > <Button android:id="@+id/id_left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="startLeftChange" android:text="StartLeft" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/id_left" android:onClick="startRightChange" android:text="StartRight" /> </LinearLayout> </RelativeLayout>
注意我们的自定义属性的命名空间,该布局就一个ColorTrackView,然后两个按钮来控制进度。
SimpleUseActivity:
package com.zhy.viewpagerIndicator; import android.animation.ObjectAnimator; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.view.View; import com.zhy.view.ColorTrackView; public class SimpleUseActivity extends Activity { ColorTrackView mView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple_main); mView = (ColorTrackView) findViewById(R.id.id_changeTextColorView); } @SuppressLint("NewApi") public void startLeftChange(View view) { mView.setDirection(0); ObjectAnimator.ofFloat(mView, "progress", 0, 1).setDuration(2000) .start(); } @SuppressLint("NewApi") public void startRightChange(View view) { mView.setDirection(1); ObjectAnimator.ofFloat(mView, "progress", 0, 1).setDuration(2000) .start(); } }
这里拿属性动画进行的测试,没有导入3.0以下兼容包,有需要自己导入。
效果图就是上面张鸿洋那张。
2、结合ViewPager
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:zhy="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal" > <com.zhy.view.ColorTrackView android:id="@+id/id_tab_01" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" zhy:progress="1" zhy:text="简介" zhy:text_change_color="#ffff0000" zhy:text_origin_color="#ff000000" zhy:text_size="18sp" /> <com.zhy.view.ColorTrackView android:id="@+id/id_tab_02" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" zhy:text="评价" zhy:text_change_color="#ffff0000" zhy:text_origin_color="#ff000000" zhy:text_size="18sp" /> <com.zhy.view.ColorTrackView android:id="@+id/id_tab_03" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" zhy:text="相关" zhy:text_change_color="#ffff0000" zhy:text_origin_color="#ff000000" zhy:text_size="18sp" /> </LinearLayout> <android.support.v4.view.ViewPager android:id="@+id/id_viewpager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" > </android.support.v4.view.ViewPager> </LinearLayout>
3个ColorTrackView代表Tab,下面是ViewPager
ViewPagerUseActivity:
package com.zhy.viewpagerIndicator; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.Log; import com.zhy.view.ColorTrackView; public class ViewPagerUseActivity extends FragmentActivity { private String[] mTitles = new String[] { "简介", "评价", "相关" }; private ViewPager mViewPager; private FragmentPagerAdapter mAdapter; private TabFragment[] mFragments = new TabFragment[mTitles.length]; private List<ColorTrackView> mTabs = new ArrayList<ColorTrackView>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_vp_main); initViews(); initDatas(); initEvents(); } private void initEvents() { mViewPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (positionOffset > 0) { ColorTrackView left = mTabs.get(position); ColorTrackView right = mTabs.get(position + 1); left.setDirection(1); right.setDirection(0); Log.e("TAG", positionOffset+""); left.setProgress( 1-positionOffset); right.setProgress(positionOffset); } } @Override public void onPageScrollStateChanged(int state) { } }); } private void initDatas() { for (int i = 0; i < mTitles.length; i++) { mFragments[i] = (TabFragment) TabFragment.newInstance(mTitles[i]); } mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public int getCount() { return mTitles.length; } @Override public Fragment getItem(int position) { return mFragments[position]; } }; mViewPager.setAdapter(mAdapter); mViewPager.setCurrentItem(0); } private void initViews() { mViewPager = (ViewPager) findViewById(R.id.id_viewpager); mTabs.add((ColorTrackView) findViewById(R.id.id_tab_01)); mTabs.add((ColorTrackView) findViewById(R.id.id_tab_02)); mTabs.add((ColorTrackView) findViewById(R.id.id_tab_03)); } }
TabFragment
package com.zhy.viewpagerIndicator; import java.util.Random; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class TabFragment extends Fragment { public static final String TITLE = "title"; private String mTitle = "Defaut Value"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mTitle = getArguments().getString(TITLE); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView tv = new TextView(getActivity()); tv.setTextSize(60); Random r = new Random(); tv.setBackgroundColor(Color.argb(r.nextInt(120), r.nextInt(255), r.nextInt(255), r.nextInt(255))); tv.setText(mTitle); tv.setGravity(Gravity.CENTER); return tv; } public static TabFragment newInstance(String title) { TabFragment tabFragment = new TabFragment(); Bundle bundle = new Bundle(); bundle.putString(TITLE, title); tabFragment.setArguments(bundle); return tabFragment; } }
效果图就是上面“结合ViewPager使用”的那张。