FC 12.6 下拉刷新
前几篇文章已经将界面写的差不多了,接下来添加下拉刷新的功能
Material Design 中制定了Android的统一的下拉刷新的风格,SwipeRefreshLayout(support-v4)是用于实现下拉刷新的核心类。
添加下拉刷新
- 修改activity_main.xml
- 在RecycleView外层嵌套SwipeRefreshLayout(由于Recycleview变成了RefreshLayout的子控件,因此需要将属性app:layout_behavior="@string/appbar_scrolling_view_behavior"放到SwipeRefreshLayout里)
- 修改MainActivity
- (通过findViewById绑定控件)
- 调用setColorSchemeResources方法来设置下来刷新进度条的颜色,这里使用了主题中的colorPrimary颜色
- 调用setOnRefreshListener方法来设置下拉刷新的监听器,在onRefresh添加我们的逻辑
- 添加refreshFruits方法作为我们刷新时的操作
- 先开启一个线程休眠2s(这样我们就可以看到刷新的动作)
- 然后使用runOnUiThread将线程切回主线程,调用initFruits方法重新生成数据
- 调用adapter的notifyDataSetChanged通知数据发生变化
- 调用setRefreshing方法,传入false表示刷新时间结束,并隐藏刷新进度条
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_Layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
...
<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" />
</android.support.v4.widget.SwipeRefreshLayout>
...
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
//此处设置滑动刷新
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();
}
运行,如图