本文說明如何在使用者要求手動重新整理時更新應用程式 (無論是透過滑動手勢觸發,或使用動作列重新整理動作)。
回應重新整理手勢
當使用者執行滑動重新整理手勢時,系統會顯示進度指標,並呼叫應用程式的回呼方法。您的回呼方法負責更新應用程式的資料。
如要回應應用程式中的重新整理手勢,請實作 SwipeRefreshLayout.OnRefreshListener
介面及其 onRefresh()
方法。使用者執行滑動手勢時,系統會叫用 onRefresh()
方法。
將實際更新作業的程式碼放在單獨的方法 (最好放在 ViewModel
) 中,並從 onRefresh()
實作呼叫該更新方法。這樣一來,您就可以在使用者從動作列觸發重新整理時,使用相同的更新方法執行更新作業。
在更新方法中,請在資料更新完畢後呼叫 setRefreshing(false)
。呼叫此方法會指示 SwipeRefreshLayout
移除進度指標並更新檢視畫面內容。
舉例來說,以下程式碼會實作 onRefresh()
並叫用 myUpdateOperation()
方法,更新 ListView
顯示的資料:
Kotlin
// Sets up a SwipeRefreshLayout.OnRefreshListener that invokes when // the user performs a swipe-to-refresh gesture. mySwipeRefreshLayout.setOnRefreshListener { Log.i(LOG_TAG, "onRefresh called from SwipeRefreshLayout") // This method performs the actual data-refresh operation and calls // setRefreshing(false) when it finishes. myUpdateOperation() }
Java
// Sets up a SwipeRefreshLayout.OnRefreshListener that is invoked when // the user performs a swipe-to-refresh gesture. mySwipeRefreshLayout.setOnRefreshListener(() -> { Log.i(LOG_TAG, "onRefresh called from SwipeRefreshLayout"); // This method performs the actual data-refresh operation and calls // setRefreshing(false) when it finishes. myUpdateOperation(); } );
回應重新整理動作
如果使用者使用動作列要求重新整理,系統會呼叫 onOptionsItemSelected()
方法。應用程式會顯示進度指標並重新整理應用程式資料,以回應這項呼叫。
如要回應重新整理動作,請覆寫 onOptionsItemSelected()
。在覆寫方法中,使用 true
值呼叫 setRefreshing()
以觸發 SwipeRefreshLayout
進度指標,然後執行更新作業。另外以不同的方法執行實際更新,因此無論使用者是滑動手勢或使用動作列觸發更新,您都可以呼叫相同方法。更新完成後,請呼叫 setRefreshing(false)
來移除重新整理進度指標。
以下程式碼顯示如何回應要求動作:
Kotlin
// Listen for option item selections to receive a notification when the user // requests a refresh by selecting the refresh action bar item. override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { // Check whether the user triggers a refresh: R.id.menu_refresh -> { Log.i(LOG_TAG, "Refresh menu item selected") // Signal SwipeRefreshLayout to start the progress indicator. mySwipeRefreshLayout.isRefreshing = true // Start the refresh background task. This method calls // setRefreshing(false) when it finishes. myUpdateOperation() return true } } // User doesn't trigger a refresh. Let the superclass handle this action. return super.onOptionsItemSelected(item) }
Java
// Listen for option item selections to receive a notification when the user // requests a refresh by selecting the refresh action bar item. @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Check whether the user triggers a refresh: case R.id.menu_refresh: Log.i(LOG_TAG, "Refresh menu item selected"); // Signal SwipeRefreshLayout to start the progress indicator. mySwipeRefreshLayout.setRefreshing(true); // Start the refresh background task. This method calls // setRefreshing(false) when it finishes. myUpdateOperation(); return true; } // User doesn't trigger a refresh. Let the superclass handle this action. return super.onOptionsItemSelected(item); }