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