Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 仿天貓下拉刷新自定義控制項深度解析

編輯:關於 Android 程式設計

一、概述

本控制項以 android-Ultra-Pull-to-Refresh 為基礎,針對其 header 進行客製化擴充。它繼承自 PtrFrameLayout,並將觸摸事件轉發給內部的 RadioGroup,因此兩個自定義控制項分別命名為 HoynPtrFrameLayout 與 HoynRadioGroup。由於需要用到 PtrFrameLayout 中的私有屬性 mPtrIndicator 與 mScrollChecker,作者乾脆把 PtrFrameLayout 的程式碼抽出來以便於定製,讓 HoynPtrFrameLayout 能夠更靈活地使用這些成員。

二、使用方式

相關的版面配置檔共有三個:layout.xml、view_header.xml 與 view_header_tab.xml。其中 layout.xml 是 Activity 的版面配置,view_header.xml 對應 RadioGroup 控制項,view_header_tab.xml 則是最上方「首頁、個人中心」等頁籤控制項。


hoynPtrFrameLayout.setHeaderView(view_header); //必須
hoynPtrFrameLayout.setTabView(tabview) //可選

layout.xml:











view_header.xml

由於定製的關係,view_header 的結構必須由一個 RelativeLayout 包裹一個 HoynRadioGroup 組成。







MainActivity

public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private HoynPtrFrameLayout hoynPtrFrameLayout; private HoynRadioGroup group; private RadioButton btn_share, btn_refresh; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout); hoynPtrFrameLayout = (HoynPtrFrameLayout) findViewById(R.id.store_house_ptr_frame); View view_header = LayoutInflater.from(this).inflate(R.layout.view_header, null); View tabview = LayoutInflater.from(this).inflate(R.layout.view_header_tab, null); tabview.findViewById(R.id.iv_home).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "點擊了首頁", Toast.LENGTH_SHORT).show(); } }); group = (HoynRadioGroup) view_header.findViewById(R.id.group); btn_share = (RadioButton) group.findViewById(R.id.radioButton1); btn_refresh = (RadioButton) group.findViewById(R.id.radioButton2); btn_share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "選擇了分享", Toast.LENGTH_SHORT).show(); } }); btn_refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "選擇了刷新", Toast.LENGTH_SHORT).show(); } }); hoynPtrFrameLayout.setHeaderView(view_header); hoynPtrFrameLayout.setTabView(tabview); hoynPtrFrameLayout.setOnFiggerUpListener(new HoynPtrFrameLayout.OnFiggerUpListener() { @Override public void onFiggerUp(int checkedId) { if (checkedId == btn_share.getId()) { //選擇分享,直接到頂部 hoynPtrFrameLayout.scrollToTop(); btn_share.performClick(); } else { //選擇刷新,顯示loading,數據讀取完,再回到頂部 hoynPtrFrameLayout.showProgressBar(); btn_refresh.performClick(); } hoynPtrFrameLayout.postDelayed(new Runnable() { @Override public void run() { hoynPtrFrameLayout.completeRefresh(); } }, 1000); } }); } } 

三、HoynRadioGroup 源碼剖析

1、構造方法

 private static final String TAG = "HoynRadioGroup"; private float down_x; private int childCount; private int currentIndex; private Paint mPaint; private int mColor = 0xFFE61A5F; private Path path; private int off_left = 0, off_right = 0; private Circle circle; private List circleList = new ArrayList<>(); private boolean isAnimating = false; //判斷動畫是否正在執行 private boolean isHeaderShow = false; //判斷下拉控件是否完全顯示出來且不超過1.5倍控件高度 private boolean isShowCircle = true; //判斷下拉過程中是否顯示圓 private boolean isChangeState = false;//圓動畫和動畫結束的切換 private boolean isShowCircleAnimation = true; //下拉過程中是否應該顯示圓的動畫 private boolean isCircleAnimating = false; //判斷顯示圓的動畫是否在執行 private static final int createCircleDuration = 150; //圓出現動畫執行時間 private static final int createCircleInterval = 10; //動畫執行頻率 private static final int animatorDuration = 100;//圓左右移動動畫執行時間 private static final int animatorInterval = 10; //動畫執行頻率 private float radius;//下拉過程中 圓動畫的半徑 private float alpha;//下拉過程中 控件的透明度 private int tabViewHeight = 0; public HoynRadioGroup(Context context) { super(context); paintInit(); } public HoynRadioGroup(Context context, AttributeSet attrs) { super(context, attrs); paintInit(); } private void paintInit() { setWillNotDraw(false); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setAlpha(100); mPaint.setColor(mColor); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.FILL); mPaint.setStrokeWidth(5); path = new Path(); } 

這段程式碼主要負責初始化工作,其中 setWillNotDraw(false) 是必須的,否則後續呼叫 invalidate() 時 onDraw 不會被觸發。

2、動畫

動畫主要分為兩部分:一是圓的顯示過程,二是圓完全顯示後,依手勢左右滑動時產生的拉伸與移動效果。

圓的顯示過程:


public void circleAnimationStart(final float from, final float to, final int duration, final boolean isShowCircle, final MotionEvent ev) { isCircleAnimating = true; if (isShowCircle) { if (duration < 0) { this.isShowCircle = isShowCircle; isAnimating = false; isChangeState = isHeaderShow; isShowCircleAnimation = false; isCircleAnimating = false; if (ev != null) down_x = ev.getX(); return; } radius = from; invalidate(); postDelayed(new Runnable() { @Override public void run() { float addInterval = to / (createCircleDuration / createCircleInterval); circleAnimationStart(from + addInterval, to, duration - createCircleInterval, isShowCircle, ev); } }, createCircleInterval); } else { if (duration < 0) { this.isShowCircle = isShowCircle; isAnimating = false; isChangeState = isHeaderShow; isShowCircleAnimation = false; isCircleAnimating = false; if (ev != null) down_x = ev.getX(); return; } radius = from; invalidate(); postDelayed(new Runnable() { @Override public void run() { float addInterval = circle.getRadius() / (createCircleDuration / createCircleInterval); circleAnimationStart(from - addInterval, to, duration - createCircleInterval, isShowCircle, ev); } }, createCircleInterval); } } 

其中 MotionEvent ev 參數的作用,是為了避免圓的顯示動畫執行期間,手指按壓位移變大後出現座標偏差。因為在動畫過程中,按下時記錄的 down_x 可能改變,導致圓顯示完畢後突然被拉扯得很大。圓的顯示動畫透過 isShowCircle 參數判斷圓是「從無到有」還是「從有到無」,並以遞迴方式每隔 createCircleInterval 執行一次。

圓的移動過程:


private void moveAnimationStart(final int index, OnAnimatorListener onAnimatorListener) { final Circle mCurrentCircle = circleList.get(index); int preX = circle.getX(); int currentX = mCurrentCircle.getX(); endX = preX; mOff_left = off_left; mOff_right = off_right; onAnimatorListener.onAnimatorStart(); animationHelper(preX, currentX, animatorDuration, onAnimatorListener); } private void animationHelper(final int preX, final int currentX, final int duration, final OnAnimatorListener onAnimatorListener) { if (duration < 0) { return; } postDelayed(new Runnable() { @Override public void run() { int mPreX = preX; int mOff_x = Math.abs(currentX - endX) / (animatorDuration / animatorInterval); int mPull_x = mOff_left > mOff_right ? mOff_left : mOff_right; int mPull_interval = Math.abs(mPull_x) / (animatorDuration / animatorInterval) * 2; if (mPreX < currentX) { mPreX += mOff_x; if (off_right > 0) { off_right -= mPull_interval; } else { off_right = 0; } if (mPreX > currentX) { mPreX = currentX; } } else { mPreX -= mOff_x; if (off_left > 0) { off_left -= mPull_interval; } else { off_left = 0; } if (mPreX < currentX) { mPreX = currentX; } } circle.setX(mPreX); invalidate(); if (mPreX != currentX) { animationHelper(mPreX, currentX, duration - animatorInterval, onAnimatorListener); } else { onAnimatorListener.onAnimatorComplete(); } } }, animatorInterval); }

與圓的顯示動畫類似,透過手勢取得起點與終點,判斷是左滑還是右滑,再計算每次移動的距離,用遞迴持續重繪圓的座標。透過 OnAnimatorListener 介面,可以在動畫開始與結束時改變 RadioButton 的勾選狀態並記錄 isAnimating 狀態。

圓的拉伸效果:


case MotionEvent.ACTION_MOVE:
int off_x = (int) (ev.getX() - down_x);
final View preChild = getChildAt(currentIndex);
if (preChild == null) { return super.dispatchTouchEvent(ev); }
int width = preChild.getWidth();
if (off_x < 0 && Math.abs(off_x) < width / 2 && currentIndex != 0) { off_left = (int) Math.abs((off_x / 1.5)); off_right = 0; }
else if (off_x > 0 && Math.abs(off_x) < width / 2 && currentIndex < childCount - 1) { off_right = (int) Math.abs((off_x / 1.5)); off_left = 0; }
invalidate();
break;

透過比較移動時的 x 座標與按下時的 x 座標得到偏移量 off_x,再依其方向與 currentIndex 的邊界判斷圓是否能被拉動(例如 index=0 時只能往右拉),進而得出左側或右側的拉伸偏移量。值得留意的是,圓在移動過程中,拉伸後的變形並非瞬間回復,而是慢慢復原,但復原速度比移動更快,因此拉伸速度 mPull_interval 是位移速度 mOff_x 的兩倍。

3、onDraw()


@Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); int width = circle.getX() < circle.getY() ? circle.getX() : circle.getY(); RectF rectLeft = null; RectF rectRight = null; if (isShowCircleAnimation) { rectLeft = new RectF(width - radius, width - radius, width + radius, width + radius); rectRight = new RectF(width - radius, width - radius, width + radius, width + radius); } else { if (isShowCircle && isHeaderShow) { rectLeft = new RectF(width - circle.getRadius() - off_left, width - circle.getRadius(), width + circle.getRadius() + off_left, width + circle.getRadius()); rectRight = new RectF(width - circle.getRadius() - off_right, width - circle.getRadius(), width + circle.getRadius() + off_right, width + circle.getRadius()); } } if (rectLeft == null) { return; } rectLeft.offset(circle.getX() - circle.getRadius(), circle.getY() - circle.getRadius()); rectRight.offset(circle.getX() - circle.getRadius(), circle.getY() - circle.getRadius()); canvas.drawArc(rectLeft, 90, 180, true, mPaint); canvas.drawArc(rectRight, 270, 180, true, mPaint); }

onDraw() 是繪製圓的關鍵。首先判斷圓的大小:由於圓必定位於控制項內部,因此取 RadioButton 寬高的較小值賦給 width。接著判斷 isShowCircleAnimation,若為 true 則繪製圓的顯示或消失,否則繪製圓的移動過程。要實現拉伸效果,需要繪製兩個半圓組成一個完整的圓,再分別控制左半圓與右半圓的寬度。由於 0° 從右側開始,因此從 90° 起繪製 180° 的弧形即可畫出左半圓,右半圓同理。在 dispatchTouchEvent 中取得 off_left 與 off_right 後,只需增減矩形 rect 的左側或右側寬度即可。

四、HoynPtrFrameLayout 源碼剖析

1、構造


private float NOT_HAS_TABVIEW_RATE = 1.8f; private boolean hasTabView = true; private HoynRadioGroup myRadioGroup; private PtrIndicator mPtrIndicator; private ScrollChecker mScrollChecker; private Paint mPaint; private float alpha; private LinearLayout progressLayout; private ProgressBar progressBar; private View tabView; private OnFiggerUpListener onFiggerUpListener; private boolean isShowTab = false; private void init() { setWillNotDraw(false); mScrollChecker = getScrollChecker(); mPtrIndicator = getPtrIndicator(); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setColor(Color.BLACK); mPaint.setAntiAlias(true); mPaint.setAlpha(0); mPaint.setStyle(Paint.Style.FILL); }

mScrollChecker 與 mPtrIndicator 是 PtrFrameLayout 中的私有物件,需把源碼複製出來並加上 getter 方法才能取得。

2、dispatchTouchEvent 傳遞觸摸事件

第一步是把事件轉發給 HoynRadioGroup,這樣左右滑動才能被接收;第二步是處理 progressBar 的顯示,刷新時讓它出現。

3、onLayout

由於 onLayout 有時會執行多次,因此在新增 progressBar 前需先判斷 progressLayout 是否為空,若已存在則更新其寬高。新增時先判斷 progressBar 是否為空,可透過 setProgressBar() 自定義,否則使用系統預設的 progressBar。

5、TabView

為 tabView 設定一個 Id(android.R.id.text1 只是隨意選取),目的是讓該元件能被找到。由於 RelativeLayout 無法讓新元件排在頂部元件之上,因此第一次 onLayout 時(tabView == null)需先 removeAllViews(),加入 tabView 後再重新把 RadioGroup 與 progressBar 補回。

6、下拉過程中的透明度變化


@Override protected void onPositionChange(boolean isInTouching, byte status, PtrIndicator mPtrIndicator) { super.onPositionChange(isInTouching, status, mPtrIndicator); alpha = (float) mPtrIndicator.getCurrentPosY() / mPtrIndicator.getHeaderHeight(); if (alpha > 0.8) { alpha = 0.8f; } if (hasTabView) { if (!isShowTab) { float tabAlpha = (mPtrIndicator.getCurrentPosY() - myRadioGroup.getHeight() - tabView.getHeight()) / (float) tabView.getHeight(); tabAlpha = tabAlpha / 1.5f; tabView.setAlpha(tabAlpha); } else { tabView.setAlpha(1); } } invalidate(); }

將 alpha 上限設為 0.8,是為了避免背景全黑,保留一些透明感;tabAlpha 除以 1.5 則是為了讓顯示更自然,透明度不會變化太快,避免還沒開始就已完全顯示或消失。由於 alpha 是全域變數,onDraw 中可直接取用。在 onDraw 裡畫一個黑色背景,其透明度隨 alpha 變化,同時讓內部元件的透明度也一併隨之改變。

至此大致完成,完整程式碼已放上 GitHub 並持續更新,歡迎關注。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved