SwipeRefreshLayout
下拉刷新,这google定义的一个规范的下拉刷新的布局控件
而实现下拉刷新的功能的核心类式由support-v4库提供的。
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycle_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
/>
</android.support.v4.widget.SwipeRefreshLayout>
将RecyclerView控件包住即可,那么此控件就具备了下拉刷新的功能。那么由于RecyclerView变成了SwipeRefreshLayout的子控件,那么其中的app:layout_behavior=”@string/appbar_scrolling_view_behavior”移动到SwipeRefreshLayout中去了。
第二部就是在代码中实现具体的刷新逻辑。
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshFruits();
}
});
}
private void refreshFruits() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
initFruits();
adapter.notifyDataSetChanged();
swipeRefresh.setRefreshing(false);
}
});
}
}).start();
}
其中的onRefresh()实际上去请求网络上的数据。