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

告別第三方庫:Android 官方下拉刷新組件 SwipeRefreshLayout 使用指南

編輯:關於 Android 程式設計

過去做下拉刷新,很多人會引入 PullToRefresh、ActionBar-PullToRefresh 這類第三方開源庫。其實從 support v4 19.1 版本開始,官方已經提供了現成的組件——SwipeRefreshLayout,它能輕鬆還原 Google Now 風格的刷新動畫。

SwipeRefreshLayout 繼承自 ViewGroup,可以包裹任意其他組件。使用官方控件的好處是通用性強、風格統一,也不必擔心依賴衝突。

一、布局寫法

它本質上是一個容器,把需要支持下拉刷新的內容(例如 ListView)放進去即可:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

實際項目中,把最外層容器換成 SwipeRefreshLayout,並將 ListView 作為其子控件:

<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/swip"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.v4.widget.SwipeRefreshLayout>

二、代碼控制

Activity 實現 OnRefreshListener 接口,在回調中處理數據刷新邏輯:

public class MainActivity extends ActionBarActivity
        implements OnRefreshListener {

    private SwipeRefreshLayout swipeRefreshLayout;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            swipeRefreshLayout.setRefreshing(false);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swip);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorScheme(
            android.R.color.holo_blue_bright,
            android.R.color.holo_green_light,
            android.R.color.holo_orange_light,
            android.R.color.holo_red_light);
    }

    @Override
    public void onRefresh() {
        // 在這裡請求數據並更新界面
        handler.sendEmptyMessageDelayed(1, 5000);
    }
}

三、關鍵要點

  • 在 onRefresh() 中發起數據請求並更新列表。
  • 數據更新完成後,務必調用 setRefreshing(false) 關閉刷新狀態,否則轉圈動畫不會停止。
  • 可以透過 setColorScheme() 自定義刷新指示器的顏色組合,讓它與產品視覺保持一致。
  • 它默認只在列表滾動到頂部時才觸發下拉手勢,與 ListView 的滾動衝突已被內部處理好。

總體來看,SwipeRefreshLayout 用法簡單、侵入性低,是替代第三方刷新庫的首選方案。

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