之前一直都想用下拉刷新,感覺上是龐大的工程,所以擱置了。現在學習了一下其實真的超級簡單。
看了《第一行代碼》以及 https://www.jianshu.com/p/3c402a9e4b7d文章
看上去是真的簡單。SwipeRefreshLayout下嵌套一個控件
1.布局代碼
<android.support.v4.widget.SwipeRefreshLayout android:id="@+id/mswipeRefreshLayout" android:layout_width="match_parent" android:layout_height="match_parent" >
<WebView android:id="@+id/mwebview" android:layout_width="match_parent" android:layout_height="match_parent"
>
</WebView>
</android.support.v4.widget.SwipeRefreshLayout>
混編的app,這里嵌套了一個webview
2.Activity代碼
mSwipe = findViewById(R.id.mswipeRefreshLayout); private void setSwipe() { /* * 設置下拉刷新球顏色 */ mSwipe.setColorSchemeResources(R.color.swipeColor1,R.color.swipeColor2,R.color.swipeColor3,R.color.swipeColor4,R.color.swipeColor5); /* * 設置下拉刷新的監聽 */ mSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { //刷新需執行的操作 } }); }
我們可以在res/values/colors.xml文件中設置我們想要的顏色
<color name="swipeColor1">#3F51B5</color>
<color name="swipeColor2">#000000</color> ......
加載完畢后需要關閉下拉刷新球
mSwipe.setRefreshing(false);
3.打開頁面自動刷新
mSwipe.measure(0,0);
mSwipe.setRefreshing(true);
在onMeasure之前 單獨使用setRefreshing(true)是沒有效果的
還可以復寫onWindowFocusChanged當頁面獲得焦點的時刷新
@Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mSwipe.setRefreshing(true); }
也可以放到ui線程消息循環中排隊
mSwipe.post(new Runnable() { @Override public void run() { mSwipe.setRefreshing(true); } });
在刷新結束后關閉刷新球
public void SwipeIsFinish(){ if (mSwipe.isRefreshing()) { mSwipe.setRefreshing(false); } }