本文件說明如何在使用者要求手動重新整理時更新應用程式,無論是使用滑動手勢或使用動作列重新整理動作皆然。
回應重新整理手勢
當使用者執行滑動手勢時,系統會顯示進度指示器,並呼叫應用程式的回呼方法。回呼方法負責更新應用程式資料。
如要回應應用程式中的重新整理手勢,請實作 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); }