1 SwipeRefreshLayout
修改布局文件,新增 SwipeRefreshLayout :<?xml version="1.0"encoding="utf-8"?>
xmlns:material="/apk/res-auto"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="match_parent">
...
android:id="@+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
material:layout_behavior="@string/appbar_scrolling_view_behavior">
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
...
...
这里我们把 RecyclerView 放在 SwipeRefreshLayout 中。
2 处理刷新
修改活动类:publicclassMainActivityextendsAppCompatActivity{privateSwipeRefreshLayoutsrl;@Override
protectedvoidonCreate(BundlesavedInstanceState){
...//处理刷新逻辑
srl=(SwipeRefreshLayout)findViewById(R.id.swipe_refresh_layout);//获取SwipeRefreshLayout实例
srl.setColorSchemeResources(R.color.colorPrimary);//设置刷新进度条颜色
srl.setOnRefreshListener(newSwipeRefreshLayout.OnRefreshListener(){//设置刷新监听器
@Override
publicvoidonRefresh(){
refresh();
}
}
);
}
/**
*刷新
*/
privatevoidrefresh(){newThread(newRunnable(){@Override
publicvoidrun(){try{
Thread.sleep(1000);//为了体现出刷新效果,所以这里休眠了线程
}catch(InterruptedExceptione){
e.printStackTrace();
}//切回主线程
runOnUiThread(newRunnable(){@Override
publicvoidrun(){
initCats();//重新生成数据
adapter.notifyDataSetChanged();//通知数据已发生变化
srl.setRefreshing(false);//当刷新事件结束时,隐藏刷新进度条
}
});
}
}).start();
}
...
}
在 onCreate 方法中:获取 SwipeRefreshLayout 实例。
设置刷新进度条颜色。
设置刷新监听器。在监听器中调用 refresh() 方法。
在 refresh 方法中:为了体现出刷新效果,所以在此休眠了线程。一般情况下,这里会与服务器进行交互,获取数据。
利用 runOnUiThread() 切回主线程。
在主线程中,重新生成数据,接着通知数据已发生变化,最后隐藏刷新进度条。
运行程序,向下拖动主界面,就会出现下拉刷新进度条,松手就会自动刷新图片:
是不是很酷呀O(∩_∩)O~
作者:deniro
链接:/p/dd4f0b4bfaca