1、概述
本篇部落格的產生呢,是因為,群裡的哥們暖暖給我發了個效果圖,然後問我該如何實現頂部ViewPager指示器的字型變色,該效果圖是這樣的:
大概是今天頭條的app,神奇的地方就在於,切換ViewPager頁面的時候,頂部指示器改成了字型顏色的變化,個人覺得還是不錯的。
那麼核心的地方就是做一個支援字型這樣逐漸染色就可以了,我大概想了32s,掃描了一些可能實現的方案,最終定位了一個靠譜的,下面我就帶大家開始實現的征程。
實現之前貼一下我們的效果圖:
2、效果圖
1、簡單使用
效果如上圖了,關於顏失色的改變我新增了兩個方向,一個是左方向,一個是有方向。
單純的使用,可能覺得沒什麼意思,下面看結合ViewPager使用的一個例子。
2、結合ViewPager使用
可以看到我們切換頁面的時候,上面的指示器的效果,棒棒噠~~~
當然了,學會了原理,你可以擴充套件,可以做個性的進度條,可以將字型變色改為背景色變色,可以把方向改為上下,太多了,自己去摳腳想把。
3、原理
看完效果圖,有木有什麼思路~~~花幾分鐘想想,因為原理很簡單~~
我大致想了下,目測繪製半個字估計不行,那麼就在繪製範圍上下功夫,你可以全部繪製,但是我控制顯示的範圍,所以上述效果:
其實是繪製了兩遍字型,但是呢,分別控制了繪製的顯示範圍,實現了逐漸變色的效果,那麼對於範圍的控制,有什麼方便的API麼,顯然是有的
canvas有個clipRect的方法~~~ok,原理分析完畢~~
4、實現
說到實現,那第一步肯定又是自定義屬性,我們這裡的屬性,需要text,textSize,textOriginColor,textChangeColor,progress,大致看一下,應該都能看出來作用吧,看不出來沒事,結合下面的程式碼。tip:我們的View叫做ColorTrackView,感謝小七的命名。
1、自定義屬性和獲取
attr.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?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的構造方法中進行獲取這些個渣渣屬性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
/** * * @author zhy * */ 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(); } |
1 2 3 4 5 |
private void measureText() { mTextWidth = (int) mPaint.measureText(mText); mPaint.getTextBounds(mText, 0, mText.length(), mTextBound); } |
可以看到我同時貼出了成員變數,大家簡單看下就行了,都比較簡單。
獲取了屬性,初始化完成一些成員變數以後,那麼應該走向我們的measure之旅了~~
2、onMeasure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
@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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
@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~~~
該View的完整程式碼:ColorTrackView
主要的方法介紹完畢,我們就該測試了。
5、測試
1、簡單測試
佈局檔案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
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以下相容包,有需要自己匯入。
效果圖,見上效果圖1。
2、結合ViewPager
佈局檔案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
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; } } |
效果圖見上效果圖2。