SwipeRefreshLayout元件隻接受一個子元件:即需要重新整理的那個元件。它使用一個偵聽機制來通知擁有該元件的監聽器有重新整理事件發生,換句話說我們的Activity必須實作通知的接口。該Activity負責處理事件重新整理和重新整理相應的視圖。一旦監聽者接收到該事件,就決定了重新整理過程中應處理的地方。如果要展示一個“重新整理動畫”,它必須調用setRefrshing(true),否則取消動畫就調用setRefreshing(false)。
- SwipeRefreshLayout在SDK的v4包下,即使用它時隻需導入v4的jar或者依賴v4即可, 在Android Studio中建立項目後即可使用。
- 建立項目設定布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mazaiting.swiperefreshlayouttest.MainActivity"
>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World!"
/>
</android.support.v4.widget.SwipeRefreshLayout>
- MainActivity中代碼:
public class MainActivity extends AppCompatActivity {
private SwipeRefreshLayout mSwipeRefreshLayout;
private TextView mTextView;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main);
mTextView = (TextView) findViewById(R.id.textView);
// 設定轉動顔色變化
mSwipeRefreshLayout.setColorSchemeResources(
android.R.color.holo_blue_dark,
android.R.color.holo_blue_light,
android.R.color.holo_green_light,
android.R.color.holo_green_light);
// 重新整理監聽
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override public void onRefresh() {
// 開始轉動
mSwipeRefreshLayout.setRefreshing(true);
new Thread(new Runnable() {
// ------------------- 開啟子線程
@Override public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
@Override public void run() {
// ------------- 主線程
// 停止轉動
mSwipeRefreshLayout.setRefreshing(false);
// 停止轉動後改變TextView文本
mTextView.setText("Success");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
}
效果圖:

效果圖.png