引言:今日头条的指示器很炫酷,随着你的滑动字体颜色可以逐渐的变化,实现方法主要是使用自定义控件结合ViewPager。
一、ViewPager onPageChangeListener研究
OnPageChangeListener分析:
ViewPager在处理滑动事件的时候要用到OnPageChangeListener,
OnPageChangeListener这个接口需要实现三个方法:(onPageScrollStateChanged、onPageScrolled 、onPageSelected)
操作步骤为从第一个页面滑动到第二个页面,运行Demo得到如下Log信息:
实现代码如下,在每个函数中都加入了Log:
public class SelectOnPageChangeListener implements OnPageChangeListener { private boolean checkIfScroll = false; public void onPageScrollStateChanged(int arg0) { if (DEBUG) { Log.d(TAG, "onPageScrollStateChanged:arg0=" + arg0); } if(arg0 == 1){ checkIfScroll = true; } else if (arg0 == 0){ checkIfScroll = false; } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if(checkIfScroll){ if (positionOffset > 0) { ColorTrackView left = colorTrackViews.get(position); ColorTrackView right = colorTrackViews.get(position + 1); left.setDirection(1); right.setDirection(0); if (DEBUG) { Log.d(TAG, "onPageScrolled:positionOffset=" + positionOffset + "|" + "position=" + position); } left.setProgress(1 - positionOffset); right.setProgress(positionOffset); } } } public void onPageSelected(int arg0) { if (DEBUG) { Log.d(TAG, "onPageSelected:arg0=" + arg0); } } }
操作步骤为从第一个页面滑动到第二个页面,运行Demo得到如下Log信息:
04-26 05:36:55.448: D/LearnActivity(1180): fragments size=5 04-26 05:36:55.580: W/EGL_genymotion(1180): eglSurfaceAttrib not implemented <strong>04-26 05:37:02.396: D/LearnActivity(1180): onPageScrollStateChanged:arg0=1</strong> 04-26 05:37:02.412: D/LearnActivity(1180): onPageScrolled:positionOffset=0.009722223|position=0 04-26 05:37:02.432: D/LearnActivity(1180): onPageScrolled:positionOffset=0.027777778|position=0 04-26 05:37:02.452: D/LearnActivity(1180): onPageScrolled:positionOffset=0.044444446|position=0 ......(省略一部分Log) 04-26 05:37:05.364: D/LearnActivity(1180): onPageScrolled:positionOffset=0.73888886|position=0 <strong>04-26 05:37:05.364: D/LearnActivity(1180): onPageScrollStateChanged:arg0=2 04-26 05:37:05.364: D/LearnActivity(1180): onPageSelected:arg0=1</strong> 04-26 05:37:05.380: D/LearnActivity(1180): onPageScrolled:positionOffset=0.76666665|position=0 04-26 05:37:05.396: D/LearnActivity(1180): onPageScrolled:positionOffset=0.79583335|position=0 04-26 05:37:05.412: D/LearnActivity(1180): onPageScrolled:positionOffset=0.825|position=0 ......(省略一部分Log) 04-26 05:37:05.728: D/LearnActivity(1180): onPageScrolled:positionOffset=0.99722224|position=0 04-26 05:37:05.748: D/LearnActivity(1180): onPageScrolled:positionOffset=0.9986111|position=0 <strong>04-26 05:37:06.012: D/LearnActivity(1180): onPageScrollStateChanged:arg0=0</strong>
1.onPageScrollStateChanged(int arg0)
此方法是在状态改变的时候调用,其中arg0这个参数
有三种状态(0、1、2),由上面的Log可以知道当你滑动页面的时候,调用顺序为1,2,0。
0表示滑动完毕,1表示按下状态, 2表示手指抬起状态。当按下ViewPager的页面时
onPageScrollStateChanged:arg0=1,这有助于我们区别你是滑动页面还是点击上部文字头标切换,从而修复ColorTrackView点击头标切换文字绘制变乱的bug。
2.onPageSelected(int arg0)
此方法当你抬起手指 onPageScrollStateChanged:arg0=2
后马上触发
onPageSelected:arg0=1
,其中的参数arg0代表选中的页面。
3.onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
当页面被按下这个方法就开始执行,直到页面滑动结束onPageScrollStateChanged:arg0=0
,期间都会调用。
其中三个参数的含义分别为:
position:当前可见页面的第一个页面,也可以理解为当前滑动页面的前一个页面position。我们从第一个页面滑动到第二个页面,这也是我们上面Log打印出来的信息为什么position=0的缘故,而不是我们想当然的觉得position为1。
positionOffset:页面偏移的百分比(取值0到1之间)
positionOffsetPixels:页面偏移的像素位置
二、使用ColorTrackView打造文字渐变指示器
首先感谢
张鸿洋,这个自定义控件是他写的,具体地址在这里:
http://blog.csdn.net/lmj623565791/article/details/44098729,我把他的这个控件代码稍微优化了一下,去除了一些没用的代码,并添加了一些注释,这个控件主要是使用了自定义View中的两步,测量和绘制也就是onMeasure和onDraw。
我们来看一下文字的绘制起点,这里用高度表示,宽度道理是一样的。这两行代码计算后正好是我们的文字绘制起点,图中的大红点。代码如下:
mTextStartX = mRealWidth / 2 - mTextWidth / 2;
canvas.drawText((String) mText, mTextStartX, getMeasuredHeight()
/ 2 + mTextBound.height() / 2, mPaint);
1.values下面的文件
attrs.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="ColorTrackView"> <attr name="text" format="string" /> <attr name="textSize" format="dimension" /> <attr name="textOriginColor" format="color|reference" /> <attr name="textChangeColor" format="color|reference" /> <attr name="progress" format="float" /> <attr name="direction"> <enum name="left" value="0" /> <enum name="right" value="1" /> </attr> </declare-styleable> </resources>
colors.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="MyWhite">#FFFFF0F5</color> <color name="MyDarkRed">#FF961F21</color> <color name="MyActiveColor">#F26C4F</color> <color name="MyGray">#50696969</color> <!-- 纳瓦白/土著白 --> <color name="navajo_white">#FFDEAD</color> <color name="black">#000000</color> <color name="gray">#696969</color> </resources>dimens.xml
<resources> <dimen name="activity_horizontal_margin">6dp</dimen> <dimen name="activity_vertical_margin">6dp</dimen> <dimen name="font_size_title">20sp</dimen> <dimen name="font_size_normal">18sp</dimen> <dimen name="font_size_big">40sp</dimen> <dimen name="font_size_biger">60sp</dimen> <dimen name="font_size_center">16sp</dimen> <dimen name="font_size_small">13sp</dimen> <dimen name="font_size_cursor">12sp</dimen> </resources>strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">CompleteTrackColorViewDemo</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> </resources>
2.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.completetrackcolorviewdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar" > <activity android:name=".LearnActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
3.layout下的文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:lhw="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@color/MyWhite" > <include layout="@layout/top_bar" /> <LinearLayout android:layout_width="match_parent" android:layout_height="30dp" android:background="@color/MyGray" android:gravity="center_vertical" android:orientation="horizontal" android:weightSum="5.0" > <com.example.completetrackcolorviewdemo.ColorTrackView android:id="@+id/ctv_1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1.0" lhw:text="DEMO" lhw:textSize="@dimen/font_size_center" lhw:textChangeColor="@color/MyDarkRed" lhw:textOriginColor="@color/black" lhw:progress="1.0" /> <com.example.completetrackcolorviewdemo.ColorTrackView android:id="@+id/ctv_2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1.0" lhw:text="DEMO" lhw:textSize="@dimen/font_size_center" lhw:textChangeColor="@color/MyDarkRed" lhw:textOriginColor="@color/black" /> <com.example.completetrackcolorviewdemo.ColorTrackView android:id="@+id/ctv_3" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1.0" lhw:text="DEMO" lhw:textSize="@dimen/font_size_center" lhw:textChangeColor="@color/MyDarkRed" lhw:textOriginColor="@color/black" /> <com.example.completetrackcolorviewdemo.ColorTrackView android:id="@+id/ctv_4" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1.0" lhw:text="DEMO" lhw:textSize="@dimen/font_size_center" lhw:textChangeColor="@color/MyDarkRed" lhw:textOriginColor="@color/black" /> <com.example.completetrackcolorviewdemo.ColorTrackView android:id="@+id/ctv_5" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1.0" lhw:text="DEMO" lhw:textSize="@dimen/font_size_center" lhw:textChangeColor="@color/MyDarkRed" lhw:textOriginColor="@color/black" /> </LinearLayout> <android.support.v4.view.ViewPager android:id="@+id/vp_activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:flipInterval="30" android:persistentDrawingCache="animation" /> </LinearLayout>fragment.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/gray" android:gravity="center" android:orientation="vertical" > <TextView android:id="@+id/tv_fragment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/MyActiveColor" android:textSize="@dimen/font_size_center" /> </LinearLayout>top_bar.xml
<?xml version="1.0" encoding="utf-8"?> <merge xmlns:android="http://schemas.android.com/apk/res/android" > <RelativeLayout android:layout_width="match_parent" android:layout_height="48dp" android:background="@color/MyDarkRed" > <TextView android:id="@+id/tv_title_back" android:layout_width="wrap_content" android:layout_height="match_parent" android:clickable="true" android:gravity="center" android:text="loading" android:layout_marginLeft="@dimen/activity_horizontal_margin" android:textColor="@color/black" android:textSize="@dimen/font_size_title" /> </RelativeLayout> </merge>
4.src下的代码片段
ColorTrackView.java
package com.example.completetrackcolorviewdemo; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; public class ColorTrackView extends View { private static final int DIRECTION_LEFT = 0; private static final int DIRECTION_RIGHT = 1; //以下定义一些默认的变量 private int mDirection = DIRECTION_LEFT; private int mTextStartX; private Paint mPaint; private int mTextOriginColor = 0xffffff;//字体改变前的颜色 private int mTextChangeColor = 0xff0000;//字体改变中的颜色 private String mText = "xx"; private int mTextSize = DisplayUtil.dip2px(getContext(), 30); //字体大小 private int mTextWidth; private int mRealWidth; private float mProgress; // 进度,从0到1之间取值 private Rect mTextBound = new Rect(); 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_textSize, mTextSize); mTextOriginColor = ta.getColor( R.styleable.ColorTrackView_textOriginColor, mTextOriginColor); mTextChangeColor = ta.getColor( R.styleable.ColorTrackView_textChangeColor, mTextChangeColor); mProgress = ta.getFloat(R.styleable.ColorTrackView_progress, 0); mDirection = ta.getInt(R.styleable.ColorTrackView_direction, mDirection); ta.recycle(); mPaint.setTextSize(mTextSize); } private void measureText() { mTextWidth = (int) mPaint.measureText(mText); //这个函数可以获取最小的包裹文字矩形,赋值到mTextBound mPaint.getTextBounds(mText, 0,mText.length(), mTextBound); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = measureWidth(widthMeasureSpec); int height = measureHeight(heightMeasureSpec); setMeasuredDimension(width, height); measureText(); 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(); break; } result = mode == MeasureSpec.AT_MOST ? Math.min(result, val) : result; return result + getPaddingLeft() + getPaddingRight(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mDirection == DIRECTION_LEFT) { drawChangeLeft(canvas); drawOriginLeft(canvas); } else if (mDirection == DIRECTION_RIGHT) { drawOriginRight(canvas); drawChangeRight(canvas); } else { System.out.println("ColorTrackView direction error"); } } private void drawChangeRight(Canvas canvas) { drawText(canvas, mTextChangeColor, (int) (mTextStartX + (1 - mProgress) * mTextWidth), mTextStartX + mTextWidth); } private void drawOriginRight(Canvas canvas) { drawText(canvas, mTextOriginColor, mTextStartX, (int) (mTextStartX + (1 - mProgress) * mTextWidth)); } private void drawChangeLeft(Canvas canvas) { drawText(canvas, mTextChangeColor, mTextStartX, (int) (mTextStartX + mProgress * mTextWidth)); } private void drawOriginLeft(Canvas canvas) { 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((String) mText, mTextStartX, getMeasuredHeight() / 2 + mTextBound.height() / 2, mPaint); canvas.restore(); } public int getDirection() { return mDirection; } public void setDirection(int mDirection) { this.mDirection = mDirection; invalidate(); //重新改变方向,需要重绘 } public int getTextOriginColor() { return mTextOriginColor; } public void setTextOriginColor(int mTextOriginColor) { this.mTextOriginColor = mTextOriginColor; invalidate(); //改变原始颜色,需要重绘 } public int getTextChangeColor() { return mTextChangeColor; } public void setTextChangeColor(int mTextChangeColor) { this.mTextChangeColor = mTextChangeColor; invalidate();//改变变化中的颜色,需要重绘 } public String getText() { return mText; } public void setText(String mText) { this.mText = mText; } public int getTextSize() { return mTextSize; } public void setTextSize(int mTextSize) { this.mTextSize = mTextSize; requestLayout();//改变字体大小,重新布局 invalidate();//改变字体大小,需要重绘 } public float getProgress() { return mProgress; } public void setProgress(float mProgress) { this.mProgress = mProgress; invalidate();//改变进度,需要重绘,实现字体渐变的效果 } }工具类DisplayUtil.java
package com.example.completetrackcolorviewdemo; import android.content.Context; public class DisplayUtil { /** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } }LearnActivity.java
package com.example.completetrackcolorviewdemo; import java.util.ArrayList; import java.util.List; //import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; public class LearnActivity extends FragmentActivity { private String TAG = "LearnActivity"; private boolean DEBUG = true; private TextView tv_back_learn_activity; private ColorTrackView ctv_1, ctv_3, ctv_2, ctv_4, ctv_5; private ViewPager vp_learn_activity; private List<Fragment> fragments;// Tab页面列表 private List<ColorTrackView> colorTrackViews; // Tab页面头标列表 // private Context context;// 上下文 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // context = LearnActivity.this; initView(); setListener(); } private void initView() { tv_back_learn_activity = (TextView) findViewById(R.id.tv_title_back); ctv_1 = (ColorTrackView) findViewById(R.id.ctv_1); ctv_2 = (ColorTrackView) findViewById(R.id.ctv_2); ctv_3 = (ColorTrackView) findViewById(R.id.ctv_3); ctv_4 = (ColorTrackView) findViewById(R.id.ctv_4); ctv_5 = (ColorTrackView) findViewById(R.id.ctv_5); tv_back_learn_activity.setText("学习DEMO"); colorTrackViews = new ArrayList<ColorTrackView>(); colorTrackViews.add(ctv_1); colorTrackViews.add(ctv_2); colorTrackViews.add(ctv_3); colorTrackViews.add(ctv_4); colorTrackViews.add(ctv_5); InitViewPager(); } private void InitViewPager() { vp_learn_activity = (ViewPager) findViewById(R.id.vp_activity_main); fragments = new ArrayList<Fragment>(); // 后面用对应的数据去填充MyFragement,这里仅仅作为一个测试循环添加 for (int i = 0; i < 5; i++) { MyFragment fragment = new MyFragment(i); fragments.add(fragment); } if (DEBUG) { Log.d(TAG, "fragments size=" + fragments.size()); } vp_learn_activity.setAdapter(new SelectFragmentPagerAdapter( getSupportFragmentManager(), fragments)); vp_learn_activity.setCurrentItem(0); vp_learn_activity .setOnPageChangeListener(new SelectOnPageChangeListener()); } /** * 头标点击监听 */ private class SelectOnClickListener implements OnClickListener { private int index = 0; public SelectOnClickListener(int i) { index = i; } public void onClick(View v) { vp_learn_activity.setCurrentItem(index); changeColorTrackViewColor(index); } } private void setListener() { tv_back_learn_activity.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LearnActivity.this.finish(); } }); ctv_1.setOnClickListener(new SelectOnClickListener(0)); ctv_2.setOnClickListener(new SelectOnClickListener(1)); ctv_3.setOnClickListener(new SelectOnClickListener(2)); ctv_4.setOnClickListener(new SelectOnClickListener(3)); ctv_5.setOnClickListener(new SelectOnClickListener(4)); } /** * 改变选中ColorTrackView的文字颜色 * * @param index * 表示选中的是那个标签(0、1、2、3) */ private void changeColorTrackViewColor(int index) { ctv_1.setDirection(0); ctv_1.setProgress(((index == 0) ? 1.0f : 0)); ctv_2.setDirection(0); ctv_2.setProgress(((index == 1) ? 1.0f : 0)); ctv_3.setDirection(0); ctv_3.setProgress(((index == 2) ? 1.0f : 0)); ctv_4.setDirection(0); ctv_4.setProgress(((index == 3) ? 1.0f : 0)); ctv_5.setDirection(0); ctv_5.setProgress(((index == 4) ? 1.0f : 0)); } @Override protected void onPause() { super.onPause(); } @Override protected void onDestroy() { super.onDestroy(); } public class SelectOnPageChangeListener implements OnPageChangeListener { private boolean checkIfScroll = false; public void onPageScrollStateChanged(int arg0) { if (DEBUG) { Log.d(TAG, "onPageScrollStateChanged:arg0=" + arg0); } if(arg0 == 1){ checkIfScroll = true; } else if (arg0 == 0){ checkIfScroll = false; } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if(checkIfScroll){ if (positionOffset > 0) { ColorTrackView left = colorTrackViews.get(position); ColorTrackView right = colorTrackViews.get(position + 1); left.setDirection(1); right.setDirection(0); if (DEBUG) { Log.d(TAG, "onPageScrolled:positionOffset=" + positionOffset + "|" + "position=" + position); } left.setProgress(1 - positionOffset); right.setProgress(positionOffset); } } } public void onPageSelected(int arg0) { if (DEBUG) { Log.d(TAG, "onPageSelected:arg0=" + arg0); } } } }MyFragment.java
package com.example.completetrackcolorviewdemo; import android.os.Bundle; import android.view.LayoutInflater; import android.support.v4.app.Fragment; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MyFragment extends Fragment { private View layout; private TextView tv; int i; public MyFragment(int i) { super(); this.i = i; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { layout = inflater.inflate(R.layout.fragment, container, false); tv = (TextView)layout.findViewById(R.id.tv_fragment); tv.setText("第"+i+"页"); return layout; } }SelectFragmentPagerAdapter.java
package com.example.completetrackcolorviewdemo; import java.util.List; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class SelectFragmentPagerAdapter extends FragmentPagerAdapter { private List<Fragment> list; public SelectFragmentPagerAdapter(FragmentManager fm, List<Fragment> list) { super(fm); this.list = list; } @Override public int getCount() { return list.size(); } @Override public Fragment getItem(int arg0) { return list.get(arg0); } }完结!