編輯:關於 Android 程式設計
下拉刷新可以說是國內 App 的標配互動,連 Google 都為此推出了 SwipeRefreshLayout。Material Design 風格在國內推行得並不順利,一方面是 4.4 仍佔主流,另一方面也有使用者習慣的因素。
看完不少關於 SwipeRefreshLayout 的分析後,我想動手做一個兼容所有控制項的下拉刷新容器——不只是 ListView,還要能包一般 View 和 ScrollView。折騰兩天終於跑通,因為目標單純,功能不多,但把下拉刷新這個核心啃下來,其餘功能日後慢慢堆疊即可。
新系統環境無法錄製合適的 GIF,只能用截圖說明。第一張是 TextView:
第二張是 ListView:
第三張是 ScrollView:
這三種是實測成功的控制項。兼容普通 View 最簡單,ListView 與 ScrollView 才是真正需要花力氣的地方。
思路
做法和主流方案一致:自訂一個 ViewGroup,把內部子控制項的 Touch 事件攔下來交給 RefreshableView 處理,透過動態改變 headView 的 marginTop 來製造下拉位移。聽起來簡單,細節卻不少——onTouch 的返回值怎麼給、子 View 自身的 marginTop 怎麼補償,都是坑。
頭部布局 refresh_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal"> <ImageView android:id="@+id/imageView_down" android:layout_width="14dp" android:layout_height="24dp" android:padding="2dp" android:src="@drawable/svg_down" /> <ProgressBar android:visibility="gone" android:id="@+id/progressBar" android:layout_width="20dp" android:layout_height="20dp" android:progressDrawable="@drawable/progressBar" /> <TextView android:padding="15dp" android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/pull_to_refresh" android:textSize="16sp" /> </LinearLayout>
核心類 RefreshableView
package com.pull2refresh; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import shike.xianrou.com.pull2refresh.R; /** * Created by cjh on 16-9-6. */ public class RefreshableView extends LinearLayout implements View.OnTouchListener { private static final String TAG = "RefreshableView"; private static final int REFRESHING = 0;//正在刷新 private static final int ORIGINAL = REFRESHING + 1;//初始狀態 private static final int RELEASE_TO_REFRESHING = ORIGINAL + 1;//釋放即將刷新的狀態 private int current_status = ORIGINAL;//當前最新狀態 private LinearLayout headView;//刷新layout private TextView textView;//刷新layout中的文字提示 private ImageView imageView;//刷新layout中的箭頭 private ProgressBar progressBar;//刷新layout中的進度條 private View view;//手指控制的下拉的View private int hideHeight;//刷新layout要隱藏的高度 private boolean isablePull;//是否可以下拉,例如當 current_status = REFRESHIING 時是不可以下拉拖拽的 private float yDown;//手指按下的坐標 private int touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();//界限值,防止手指誤觸,過於靈敏 private boolean firstLayout = true;//第一次調用onLayout的時候置為false private int maxMarginTop;//刷新Layout能拉下的最大距離 private MarginLayoutParams marginLayoutParams;//刷新layout的MarginLayoutParams private String pull_to_refresh = "下拉可以刷新"; private String release_to_refresh = "釋放立即刷新"; private String refreshing = "正在刷新…"; private int original_margin = 0;//針對下拉的View存在MarginTop這中特殊值的處理 public interface PullToRefreshListener { void onRefresh(); } private PullToRefreshListener pullToRefreshListener; public void addPullToRefreshListener(PullToRefreshListener pullToRefreshListener) { this.pullToRefreshListener = pullToRefreshListener; } public RefreshableView(Context context) { super(context); init(); } public RefreshableView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public RefreshableView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public RefreshableView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { headView = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.refresh_layout, null, true); imageView = (ImageView) headView.findViewById(R.id.imageView_down); progressBar = (ProgressBar) headView.findViewById(R.id.progressBar); textView = (TextView) headView.findViewById(R.id.textView); progressBar.setVisibility(View.GONE); setOrientation(VERTICAL); addView(headView, 0); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); Log.d(TAG, "onlayout"); if (changed && firstLayout) { //將View的Touch時間的處理交給RefreshableView去處理 view = getChildAt(1); view.setOnTouchListener(this); //刷新layout的 marginTop 的最大值設為刷新頭的高度 maxMarginTop = headView.getHeight(); //要將控件完全隱藏起來,那麼隱藏的高度就設置為控件的高度 hideHeight = -headView.getHeight(); marginLayoutParams = (MarginLayoutParams) headView.getLayoutParams(); marginLayoutParams.topMargin = hideHeight; headView.setLayoutParams(marginLayoutParams); //這裡必須將firstLayout設置為false,否則在處理Touch是件的過程中,headView在怎麼調用setLayoutParams都會被置為初始的隱藏狀態 firstLayout = false; //如果子View是一個ViewGroup 那麼就需要計算出子View的MarginTop的值,因為如果MarginTop不為0,那麼子View的Y軸坐標和父View的坐標是不一樣的 if (view instanceof ViewGroup) { int[] childLocations = new int[2]; int[] viewLocations = new int[2]; view.getLocationOnScreen(viewLocations); ((ViewGroup) view).getChildAt(0).getLocationOnScreen(childLocations); original_margin = childLocations[1] - viewLocations[1]; Log.d(TAG, "onLayout viewLocations[1] " + viewLocations[1]); Log.d(TAG, "onLayout locations[1] " + childLocations[1]); Log.d(TAG, "onLayout original_margin " + original_margin); } } } @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (pullToRefreshListener != null) { isAblePull(); if (isablePull) { switch (motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: yDown = motionEvent.getRawY(); break; case MotionEvent.ACTION_MOVE: float yMove = motionEvent.getRawY(); float distance = yMove - yDown; //如果手勢是向上的,並且手勢在Y軸的移動距離小於界限值,那麼就不處理 if (distance < 0 || Math.abs(distance) < touchSlop) return false; //MarginTop的距離是手勢距離的1/2,形成費力延遲的效果 marginLayoutParams.topMargin = (int) (distance / 2 + hideHeight); Log.d(TAG, "topMargin " + marginLayoutParams.topMargin); //如果大於最大的MarginTop的值的時候,就將值置為 maxMarginTop if (marginLayoutParams.topMargin >= maxMarginTop) marginLayoutParams.topMargin = maxMarginTop; if (marginLayoutParams.topMargin >= 0) { //當刷新頭完全顯示的時候,改變狀態,置為 釋放刷新的狀態 if (current_status != RELEASE_TO_REFRESHING) { rotate(0, 180); textView.setText(release_to_refresh); } current_status = RELEASE_TO_REFRESHING; } else { //否則就置為初始狀態 if (current_status != ORIGINAL) { rotate(180, 360); textView.setText(pull_to_refresh); } current_status = ORIGINAL; } headView.setLayoutParams(marginLayoutParams); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: float yUp = motionEvent.getRawY(); float dis = yUp - yDown; if (dis > 0 && Math.abs(dis) > touchSlop) switch (current_status) { //釋放刷新 case RELEASE_TO_REFRESHING: animateMarginTop(marginLayoutParams.topMargin, 0); imageView.clearAnimation(); imageView.setVisibility(View.GONE); progressBar.setVisibility(View.VISIBLE); textView.setText(refreshing); pullToRefreshListener.onRefresh(); break; //初始化 case ORIGINAL: reset(); //從當前的MarginTop的值,轉變到隱藏所需的 MarginTop animateMarginTop(marginLayoutParams.topMargin, hideHeight); break; } else return false; break; } return true; } } return false; } /** * 判斷是否可以下拉 * * @return */ public boolean isAblePull() { //統一判斷,其實主要是對於view是普通View的判斷 if (current_status != REFRESHING) isablePull = true; else isablePull = false; if (view instanceof ViewGroup) { isablePull = false; View childView = ((ViewGroup) view).getChildAt(0); int[] viewLocations = new int[2]; int[] childViewLocations = new int[2]; view.getLocationOnScreen(viewLocations); childView.getLocationOnScreen(childViewLocations); //這一步中的 original_margin 至關重要,就是用來兼容 子View 有MarginTop屬性的值,當childView 的Y軸坐標 和 計算出了 Margin 值後的父View坐標相等時,說明此時處於可下拉的狀態 if (viewLocations[1] + original_margin == childViewLocations[1]) isablePull = true; else isablePull = false; } return isablePull; } private void rotate(int from, int to) { RotateAnimation rotateAnimation = new RotateAnimation(from, to, imageView.getWidth() / 2, imageView.getHeight() / 2); rotateAnimation.setDuration(100); rotateAnimation.setFillAfter(true); imageView.startAnimation(rotateAnimation); } private void animateMarginTop(int from, int to) { ObjectAnimator objectAnimator = ObjectAnimator.ofInt(headView, "cjh", from, to); objectAnimator.setDuration(300); objectAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { int margin = (int) valueAnimator.getAnimatedValue(); marginLayoutParams.topMargin = margin; headView.setLayoutParams(marginLayoutParams); } }); objectAnimator.start(); } public void complete() { animateMarginTop(0, hideHeight); reset(); } private void reset() { rotate(180, 360); textView.setText(pull_to_refresh); imageView.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); } }
這裡有幾個設計細節值得單獨拎出來:
· firstLayout 旗標:初始化只能在首次 onLayout 時做一次,否則後續每次 setLayoutParams 都會把 headView 打回隱藏狀態,下拉永遠拉不動;
· original_margin 補償:子 View 若本身設了 marginTop,它的螢幕座標會與父容器不一致,必須用「子 View 的第一個孩子座標 − 子 View 座標」量出這個差值,後續判斷是否已在頂端時再加回去,否則 ScrollView 有 marginTop 的場景會直接失效;
· 手勢門檻:用 ViewConfiguration.getScaledTouchSlop() 過濾誤觸,向上滑動或位移不足一律放行給子 View;
· 阻尼係數:marginTop 只取手勢距離的一半,做出「越拉越費力」的手感。
使用方式
<com.pull2refresh.RefreshableView android:id="@+id/refreshableView" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center"> <com.pull2refresh.MTextView android:id="@+id/mTextView" android:layout_width="match_parent" android:layout_height="100dp" android:background="@color/colorPrimary" android:gravity="center" android:text="Hello World!" android:textSize="22sp" /> </com.pull2refresh.RefreshableView>
... refreshableView.addPullToRefreshListener(new RefreshableView.PullToRefreshListener() { @Override public void onRefresh() { setData(); } }); ... private void setData() { ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(textView, "text", 1f, 100f); objectAnimator.setDuration(3000); objectAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { textView.setText((Float) valueAnimator.getAnimatedValue()); } }); objectAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { refreshableView.complete(); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); objectAnimator.start(); }
要特別注意:不呼叫 addPullToRefreshListener() 設定監聽,RefreshableView 就完全不響應下拉手勢(onTouch 開頭那個 null 判斷)。這是有意的設計——沒人接收刷新回呼,攔截手勢就毫無意義。業務處理完畢後記得呼叫 complete(),它會把頭部動畫收回並重置狀態。
原始碼下載:Android 下拉刷新控制項
以上就是本文的全部內容,希望對大家有所幫助。
SharedPreferences 儲存設定
SharedPreferences 提供簡單的鍵值儲存方式,很適合保存設定、開關狀態或小型資料。寫入先取得 SharedPreferences,再透過 Editor 呼叫
Android 音樂播放器實作:為專輯封面加上優雅倒影效果
今天要實作的功能,是為音樂播放器的專輯封面加上倒影效果。這部分已經屬於圖像處理的範疇,說實話我在圖像處理上並不算拿手,不過接下來會介紹一個非常實用的工具類,專門用來做各種
Android 閃屏實作大全(普通、倒計時、倒計時+動畫三種方案)
閃屏是幾乎每個 App 的標配。本文把常見的三種閃屏實作方式一次整理出來,供大家參考。 一、專案目錄結構 二、activity_main.xml 程式碼 <Re
Android Activity 詳解:生命週期、多種啟動方式、狀態保存與完全退出
一、什麼是 Activity?簡單地說,Activity 就是布滿整個視窗、或懸浮於其他視窗之上的互動介面。一個應用程式通常由多個 Activity 構成,且都會在 Ma