Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android應用中仿今日頭條App制作ViewPager指示器

Android應用中仿今日頭條App制作ViewPager指示器

編輯:關於Android編程

一、概述
頂部ViewPager指示器的字體變色,該效果圖是這樣的:

2016419161403484.jpg (540×960)

大概是今天頭條的app,神奇的地方就在於,切換ViewPager頁面的時候,頂部指示器改成了字體顏色的變化,個人覺得還是不錯的。
那麼核心的地方就是做一個支持字體這樣逐漸染色就可以了,我大概想了32s,掃描了一些可能實現的方案,最終定位了一個靠譜的,下面我就帶大家開始實現的征程。
實現之前貼一下我們的效果圖:
1、簡單使用

2016419161454304.gif (425×620)

效果如上圖了,關於顏失色的改變我添加了兩個方向,一個是左方向,一個是有方向。
單純的使用,可能覺得沒什麼意思,下面看結合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使用”的那張。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved