SwipeRefreshLayout組件只接受一個(gè)子組件:即需要刷新的那個(gè)組件。它使用一個(gè)偵聽機(jī)制來通知擁有該組件的監(jiān)聽器有刷新事件發(fā)生,換句話說我們的Activity必須實(shí)現(xiàn)通知的接口。該Activity負(fù)責(zé)處理事件刷新和刷新相應(yīng)的視圖。一旦監(jiān)聽者接收到該事件,就決定了刷新過程中應(yīng)處理的地方。如果要展示一個(gè)“刷新動(dòng)畫”,它必須調(diào)用setRefrshing(true),否則取消動(dòng)畫就調(diào)用setRefreshing(false)。
SwipeRefreshLayout在SDK的v4包下,即使用它時(shí)只需導(dǎo)入v4的jar或者依賴v4即可, 在Android Studio中新建項(xiàng)目后即可使用。
新建項(xiàng)目設(shè)置布局:
<?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);
// 設(shè)置轉(zhuǎn)動(dòng)顏色變化
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);
// 刷新監(jiān)聽
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override public void onRefresh() {
// 開始轉(zhuǎn)動(dòng)
mSwipeRefreshLayout.setRefreshing(true);
new Thread(new Runnable() {
// ------------------- 開啟子線程
@Override public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
@Override public void run() {
// ------------- 主線程
// 停止轉(zhuǎn)動(dòng)
mSwipeRefreshLayout.setRefreshing(false);
// 停止轉(zhuǎn)動(dòng)后改變TextView文本
mTextView.setText("Success");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
}
效果圖:

效果圖.png