Android自定義控件下拉刷新實(shí)例代碼
實(shí)現(xiàn)效果:
圖片素材:
--> 首先, 寫先下拉刷新時(shí)的刷新布局 pull_to_refresh.xml:
<resources> <string name="app_name">PullToRefreshTest</string> <string name="pull_to_refresh">下拉可以刷新</string> <string name="release_to_refresh">釋放立即刷新</string> <string name="refreshing">正在刷新...</string> <string name="not_updated_yet">暫未更新過</string> <string name="updated_at">上次更新于%1$s前</string> <string name="updated_just_now">剛剛更新</string> <string name="time_error">時(shí)間有問題</string> </resources> <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pull_to_refresh_head" android:layout_width="match_parent" android:layout_height="60dp"> <LinearLayout android:layout_width="200dp" android:layout_height="60dp" android:layout_centerInParent="true" android:orientation="horizontal"> <RelativeLayout android:layout_width="0dp" android:layout_height="60dp" android:layout_weight="3"> <ImageView android:id="@+id/arrow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@mipmap/indicator_arrow" /> <ProgressBar android:id="@+id/progress_bar" android:layout_width="30dp" android:layout_height="30dp" android:layout_centerInParent="true" android:visibility="gone" /> </RelativeLayout> <LinearLayout android:layout_width="0dp" android:layout_height="60dp" android:layout_weight="12" android:orientation="vertical"> <TextView android:id="@+id/description" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="center_horizontal|bottom" android:text="@string/pull_to_refresh" /> <TextView android:id="@+id/updated_at" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="center_horizontal|top" android:text="@string/updated_at" /> </LinearLayout> </LinearLayout> </RelativeLayout>
strings pull_to_refresh --> 然后, 也是主要的, 自定義下拉刷新的 View (包含下拉刷新所有操作) RefreshView.java: package com.dragon.android.tofreshlayout; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.SystemClock; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; public class RefreshView extends LinearLayout implements View.OnTouchListener { private static final String TAG = RefreshView.class.getSimpleName(); public enum PULL_STATUS { STATUS_PULL_TO_REFRESH(0), // 下拉狀態(tài) STATUS_RELEASE_TO_REFRESH(1), // 釋放立即刷新狀態(tài) STATUS_REFRESHING(2), // 正在刷新狀態(tài) STATUS_REFRESH_FINISHED(3); // 刷新完成或未刷新狀態(tài) private int status; // 狀態(tài) PULL_STATUS(int value) { this.status = value; } public int getValue() { return this.status; } } // 下拉頭部回滾的速度 public static final int SCROLL_SPEED = -20; // 一分鐘的毫秒值,用于判斷上次的更新時(shí)間 public static final long ONE_MINUTE = 60 * 1000; // 一小時(shí)的毫秒值,用于判斷上次的更新時(shí)間 public static final long ONE_HOUR = 60 * ONE_MINUTE; // 一天的毫秒值,用于判斷上次的更新時(shí)間 public static final long ONE_DAY = 24 * ONE_HOUR; // 一月的毫秒值,用于判斷上次的更新時(shí)間 public static final long ONE_MONTH = 30 * ONE_DAY; // 一年的毫秒值,用于判斷上次的更新時(shí)間 public static final long ONE_YEAR = 12 * ONE_MONTH; // 上次更新時(shí)間的字符串常量,用于作為 SharedPreferences 的鍵值 private static final String UPDATED_AT = "updated_at"; // 下拉刷新的回調(diào)接口 private PullToRefreshListener mListener; private SharedPreferences preferences; // 用于存儲(chǔ)上次更新時(shí)間 private View header; // 下拉頭的View private ListView listView; // 需要去下拉刷新的ListView private ProgressBar progressBar; // 刷新時(shí)顯示的進(jìn)度條 private ImageView arrow; // 指示下拉和釋放的箭頭 private TextView description; // 指示下拉和釋放的文字描述 private TextView updateAt; // 上次更新時(shí)間的文字描述 private MarginLayoutParams headerLayoutParams; // 下拉頭的布局參數(shù) private long lastUpdateTime; // 上次更新時(shí)間的毫秒值 // 為了防止不同界面的下拉刷新在上次更新時(shí)間上互相有沖突,使用id來做區(qū)分 private int mId = -1; private int hideHeaderHeight; // 下拉頭的高度 /** * 當(dāng)前處理什么狀態(tài),可選值有 STATUS_PULL_TO_REFRESH, STATUS_RELEASE_TO_REFRESH, STATUS_REFRESHING 和 STATUS_REFRESH_FINISHED */ private PULL_STATUS currentStatus = PULL_STATUS.STATUS_REFRESH_FINISHED; // 記錄上一次的狀態(tài)是什么,避免進(jìn)行重復(fù)操作 private PULL_STATUS lastStatus = currentStatus; private float yDown; // 手指按下時(shí)的屏幕縱坐標(biāo) private int touchSlop; // 在被判定為滾動(dòng)之前用戶手指可以移動(dòng)的最大值。 private boolean loadOnce; // 是否已加載過一次layout,這里onLayout中的初始化只需加載一次 private boolean ableToPull; // 當(dāng)前是否可以下拉,只有ListView滾動(dòng)到頭的時(shí)候才允許下拉 /** * 下拉刷新控件的構(gòu)造函數(shù),會(huì)在運(yùn)行時(shí)動(dòng)態(tài)添加一個(gè)下拉頭的布局 */ public RefreshView(Context context, AttributeSet attrs) { super(context, attrs); preferences = PreferenceManager.getDefaultSharedPreferences(context); header = LayoutInflater.from(context).inflate(R.layout.pull_to_refresh, null, true); progressBar = (ProgressBar) header.findViewById(R.id.progress_bar); arrow = (ImageView) header.findViewById(R.id.arrow); description = (TextView) header.findViewById(R.id.description); updateAt = (TextView) header.findViewById(R.id.updated_at); touchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); refreshUpdatedAtValue(); setOrientation(VERTICAL); addView(header, 0); //Log.d(TAG, "RefreshView Constructor() getChildAt(0): " + getChildAt(0)); //Log.d(TAG, "RefreshView Constructor() getChildAt(0): " + getChildAt(1)); // listView = (ListView) getChildAt(1); // listView.setOnTouchListener(this); } /** * 進(jìn)行一些關(guān)鍵性的初始化操作,比如:將下拉頭向上偏移進(jìn)行隱藏,給 ListView 注冊 touch 事件 */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (changed && !loadOnce) { hideHeaderHeight = -header.getHeight(); headerLayoutParams = (MarginLayoutParams) header.getLayoutParams(); headerLayoutParams.topMargin = hideHeaderHeight; listView = (ListView) getChildAt(1); //Log.d(TAG, "onLayout() getChildAt(0): " + getChildAt(0)); //Log.d(TAG, "onLayout() listView: " + listView); listView.setOnTouchListener(this); loadOnce = true; } } /** * 當(dāng) ListView 被觸摸時(shí)調(diào)用,其中處理了各種下拉刷新的具體邏輯 */ @Override public boolean onTouch(View v, MotionEvent event) { setCanAbleToPull(event); // 判斷是否可以下拉 if (ableToPull) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: yDown = event.getRawY(); break; case MotionEvent.ACTION_MOVE: // 獲取移動(dòng)中的 Y 軸的位置 float yMove = event.getRawY(); // 獲取從按下到移動(dòng)過程中移動(dòng)的距離 int distance = (int) (yMove - yDown); // 如果手指是上滑狀態(tài),并且下拉頭是完全隱藏的,就屏蔽下拉事件 if (distance <= 0 && headerLayoutParams.topMargin <= hideHeaderHeight) { return false; } if (distance < touchSlop) { return false; } // 判斷是否已經(jīng)在刷新狀態(tài) if (currentStatus != PULL_STATUS.STATUS_REFRESHING) { // 判斷設(shè)置的 topMargin 是否 > 0, 默認(rèn)初始設(shè)置為 -header.getHeight() if (headerLayoutParams.topMargin > 0) { currentStatus = PULL_STATUS.STATUS_RELEASE_TO_REFRESH; } else { // 否則狀態(tài)為下拉中的狀態(tài) currentStatus = PULL_STATUS.STATUS_PULL_TO_REFRESH; } // 通過偏移下拉頭的 topMargin 值,來實(shí)現(xiàn)下拉效果 headerLayoutParams.topMargin = (distance / 2) + hideHeaderHeight; header.setLayoutParams(headerLayoutParams); } break; case MotionEvent.ACTION_UP: default: if (currentStatus == PULL_STATUS.STATUS_RELEASE_TO_REFRESH) { // 松手時(shí)如果是釋放立即刷新狀態(tài),就去調(diào)用正在刷新的任務(wù) new RefreshingTask().execute(); } else if (currentStatus == PULL_STATUS.STATUS_PULL_TO_REFRESH) { // 松手時(shí)如果是下拉狀態(tài),就去調(diào)用隱藏下拉頭的任務(wù) new HideHeaderTask().execute(); } break; } // 時(shí)刻記得更新下拉頭中的信息 if (currentStatus == PULL_STATUS.STATUS_PULL_TO_REFRESH || currentStatus == PULL_STATUS.STATUS_RELEASE_TO_REFRESH) { updateHeaderView(); // 當(dāng)前正處于下拉或釋放狀態(tài),要讓 ListView 失去焦點(diǎn),否則被點(diǎn)擊的那一項(xiàng)會(huì)一直處于選中狀態(tài) listView.setPressed(false); listView.setFocusable(false); listView.setFocusableInTouchMode(false); lastStatus = currentStatus; // 當(dāng)前正處于下拉或釋放狀態(tài),通過返回 true 屏蔽掉 ListView 的滾動(dòng)事件 return true; } } return false; } /** * 給下拉刷新控件注冊一個(gè)監(jiān)聽器 * * @param listener 監(jiān)聽器的實(shí)現(xiàn) * @param id 為了防止不同界面的下拉刷新在上次更新時(shí)間上互相有沖突,不同界面在注冊下拉刷新監(jiān)聽器時(shí)一定要傳入不同的 id */ public void setOnRefreshListener(PullToRefreshListener listener, int id) { mListener = listener; mId = id; } /** * 當(dāng)所有的刷新邏輯完成后,記錄調(diào)用一下,否則你的 ListView 將一直處于正在刷新狀態(tài) */ public void finishRefreshing() { currentStatus = PULL_STATUS.STATUS_REFRESH_FINISHED; preferences.edit().putLong(UPDATED_AT + mId, System.currentTimeMillis()).commit(); new HideHeaderTask().execute(); } /** * 根據(jù)當(dāng)前 ListView 的滾動(dòng)狀態(tài)來設(shè)定 {@link #ableToPull} * 的值,每次都需要在 onTouch 中第一個(gè)執(zhí)行,這樣可以判斷出當(dāng)前應(yīng)該是滾動(dòng) ListView,還是應(yīng)該進(jìn)行下拉 */ private void setCanAbleToPull(MotionEvent event) { View firstChild = listView.getChildAt(0); if (firstChild != null) { // 獲取 ListView 中第一個(gè)Item的位置 int firstVisiblePos = listView.getFirstVisiblePosition(); // 判斷第一個(gè)子控件的 Top 是否和第一個(gè) Item 位置相等 if (firstVisiblePos == 0 && firstChild.getTop() == 0) { if (!ableToPull) { // getRawY() 獲得的是相對屏幕 Y 方向的位置 yDown = event.getRawY(); } // 如果首個(gè)元素的上邊緣,距離父布局值為 0,就說明 ListView 滾動(dòng)到了最頂部,此時(shí)應(yīng)該允許下拉刷新 ableToPull = true; } else { if (headerLayoutParams.topMargin != hideHeaderHeight) { headerLayoutParams.topMargin = hideHeaderHeight; header.setLayoutParams(headerLayoutParams); } ableToPull = false; } } else { // 如果 ListView 中沒有元素,也應(yīng)該允許下拉刷新 ableToPull = true; } } /** * 更新下拉頭中的信息 */ private void updateHeaderView() { if (lastStatus != currentStatus) { if (currentStatus == PULL_STATUS.STATUS_PULL_TO_REFRESH) { description.setText(getResources().getString(R.string.pull_to_refresh)); arrow.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); rotateArrow(); } else if (currentStatus == PULL_STATUS.STATUS_RELEASE_TO_REFRESH) { description.setText(getResources().getString(R.string.release_to_refresh)); arrow.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); rotateArrow(); } else if (currentStatus == PULL_STATUS.STATUS_REFRESHING) { description.setText(getResources().getString(R.string.refreshing)); progressBar.setVisibility(View.VISIBLE); arrow.clearAnimation(); arrow.setVisibility(View.GONE); } refreshUpdatedAtValue(); } } /** * 根據(jù)當(dāng)前的狀態(tài)來旋轉(zhuǎn)箭頭 */ private void rotateArrow() { float pivotX = arrow.getWidth() / 2f; float pivotY = arrow.getHeight() / 2f; float fromDegrees = 0f; float toDegrees = 0f; if (currentStatus == PULL_STATUS.STATUS_PULL_TO_REFRESH) { fromDegrees = 180f; toDegrees = 360f; } else if (currentStatus == PULL_STATUS.STATUS_RELEASE_TO_REFRESH) { fromDegrees = 0f; toDegrees = 180f; } RotateAnimation animation = new RotateAnimation(fromDegrees, toDegrees, pivotX, pivotY); animation.setDuration(100); animation.setFillAfter(true); arrow.startAnimation(animation); } /** * 刷新下拉頭中上次更新時(shí)間的文字描述 */ private void refreshUpdatedAtValue() { lastUpdateTime = preferences.getLong(UPDATED_AT + mId, -1); long currentTime = System.currentTimeMillis(); long timePassed = currentTime - lastUpdateTime; long timeIntoFormat; String updateAtValue; if (lastUpdateTime == -1) { updateAtValue = getResources().getString(R.string.not_updated_yet); } else if (timePassed < 0) { updateAtValue = getResources().getString(R.string.time_error); } else if (timePassed < ONE_MINUTE) { updateAtValue = getResources().getString(R.string.updated_just_now); } else if (timePassed < ONE_HOUR) { timeIntoFormat = timePassed / ONE_MINUTE; String value = timeIntoFormat + "分鐘"; updateAtValue = String.format(getResources().getString(R.string.updated_at), value); } else if (timePassed < ONE_DAY) { timeIntoFormat = timePassed / ONE_HOUR; String value = timeIntoFormat + "小時(shí)"; updateAtValue = String.format(getResources().getString(R.string.updated_at), value); } else if (timePassed < ONE_MONTH) { timeIntoFormat = timePassed / ONE_DAY; String value = timeIntoFormat + "天"; updateAtValue = String.format(getResources().getString(R.string.updated_at), value); } else if (timePassed < ONE_YEAR) { timeIntoFormat = timePassed / ONE_MONTH; String value = timeIntoFormat + "個(gè)月"; updateAtValue = String.format(getResources().getString(R.string.updated_at), value); } else { timeIntoFormat = timePassed / ONE_YEAR; String value = timeIntoFormat + "年"; updateAtValue = String.format(getResources().getString(R.string.updated_at), value); } updateAt.setText(updateAtValue); } /** * 正在刷新的任務(wù),在此任務(wù)中會(huì)去回調(diào)注冊進(jìn)來的下拉刷新監(jiān)聽器 */ class RefreshingTask extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { int topMargin = headerLayoutParams.topMargin; while (true) { topMargin = topMargin + SCROLL_SPEED; if (topMargin <= 0) { topMargin = 0; break; } publishProgress(topMargin); SystemClock.sleep(10); } currentStatus = PULL_STATUS.STATUS_REFRESHING; publishProgress(0); if (mListener != null) { mListener.onRefresh(); } return null; } @Override protected void onProgressUpdate(Integer... topMargin) { updateHeaderView(); headerLayoutParams.topMargin = topMargin[0]; header.setLayoutParams(headerLayoutParams); } } /** * 隱藏下拉頭的任務(wù),當(dāng)未進(jìn)行下拉刷新或下拉刷新完成后,此任務(wù)將會(huì)使下拉頭重新隱藏 */ class HideHeaderTask extends AsyncTask<Void, Integer, Integer> { @Override protected Integer doInBackground(Void... params) { int topMargin = headerLayoutParams.topMargin; while (true) { topMargin = topMargin + SCROLL_SPEED; if (topMargin <= hideHeaderHeight) { topMargin = hideHeaderHeight; break; } publishProgress(topMargin); SystemClock.sleep(10); } return topMargin; } @Override protected void onProgressUpdate(Integer ... topMargin) { headerLayoutParams.topMargin = topMargin[0]; header.setLayoutParams(headerLayoutParams); } @Override protected void onPostExecute(Integer topMargin) { headerLayoutParams.topMargin = topMargin; header.setLayoutParams(headerLayoutParams); currentStatus = PULL_STATUS.STATUS_REFRESH_FINISHED; } } /** * 下拉刷新的監(jiān)聽器,使用下拉刷新的地方應(yīng)該注冊此監(jiān)聽器來獲取刷新回調(diào) */ public interface PullToRefreshListener { // 刷新時(shí)會(huì)去回調(diào)此方法,在方法內(nèi)編寫具體的刷新邏輯。注意此方法是在子線程中調(diào)用的, 可以不必另開線程來進(jìn)行耗時(shí)操作 void onRefresh(); } }
--> 第三步, 寫主布局:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <com.dragon.android.tofreshlayout.RefreshView android:id="@+id/refreshable_view" android:layout_width="match_parent" android:layout_height="match_parent" > <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView> </com.dragon.android.tofreshlayout.RefreshView> </RelativeLayout>
--> 最后, Java 代碼添加 ListView 的數(shù)據(jù):
package com.dragon.android.tofreshlayout; import android.os.Bundle; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.webkit.WebView; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends AppCompatActivity { RefreshView refreshableView; ListView listView; ArrayAdapter<String> adapter; private WebView webView; private static int NUM = 30; String[] items = new String[NUM]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().hide(); for (int i = 0; i < items.length; i++) { items[i] = "列表項(xiàng)" + i; } refreshableView = (RefreshView) findViewById(R.id.refreshable_view); listView = (ListView) findViewById(R.id.list_view); adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items); listView.setAdapter(adapter); refreshableView.setOnRefreshListener(new RefreshView.PullToRefreshListener() { @Override public void onRefresh() { SystemClock.sleep(3000); refreshableView.finishRefreshing(); } }, 0); } }
程序 Demo: 鏈接:http://pan.baidu.com/s/1ge6Llw3 密碼:skna
***************其實(shí)還應(yīng)該再封裝的...*****************
以上所述是小編給大家介紹的Android自定義控件下拉刷新實(shí)例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Android中ListView下拉刷新的實(shí)現(xiàn)方法實(shí)例分析
這篇文章主要介紹了Android中ListView下拉刷新的實(shí)現(xiàn)方法,涉及Android操作ListView的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10Android的Service應(yīng)用程序組件基本編寫方法
Service是一個(gè)android 系統(tǒng)中的應(yīng)用程序組件,它跟Activity的級別差不多,但是他沒有圖形化界面,不能自己運(yùn)行,只能后臺(tái)運(yùn)行,Service通常用來處理一些耗時(shí)比較長的操作2012-12-12Android開啟ADB網(wǎng)絡(luò)調(diào)試方法
今天小編就為大家分享一篇Android開啟ADB網(wǎng)絡(luò)調(diào)試方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08Android onSaveInstanceState和onRestoreInstanceState觸發(fā)的時(shí)機(jī)
這篇文章主要介紹了Android onSaveInstanceState和onRestoreInstanceState觸發(fā)的時(shí)機(jī)的相關(guān)資料,需要的朋友可以參考下2017-05-05Android自定義LinearLayout布局顯示不完整的解決方法
這篇文章主要給大家介紹了關(guān)于Android自定義LinearLayout但布局顯示不完整的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11Flutter數(shù)字切換動(dòng)畫實(shí)現(xiàn)示例詳解
這篇文章主要為大家介紹了Flutter數(shù)字切換動(dòng)畫實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08