一.recyclerView控件 布局里面放上 RecyclerView
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
></android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
二.获取swipeRefreshLayout
swipeRefreshLayout= (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout); //创建swiperefresh_layout下拉刷新的对象
三.初始化swipeRefreshLayout 使用子线程加载list模拟刷新数据
/**
* swipeRefreshLayout下拉刷新按钮的控件
*/
private void initSwipeRefreshLayout(){
swipeRefreshLayout.setColorSchemeResources(R.color.red); //设置旋转按钮的颜色
swipeRefreshLayout.setDistanceToTriggerSync(100); //下拉刷新的距离
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.white)); //设置背景颜色
swipeRefreshLayout.setSize(SwipeRefreshLayout.LARGE); //设置刷新按钮的大小
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { //设置下拉刷新的监听器,要异步处理
@Override
public void onRefresh() {
final Thread thread=new Thread(new Runnable() {
@Override
public void run() {
Message msg=new Message();
msg.what=1;
RecyclorBean recyclorBean=new RecyclorBean(1,"新添加的物品",
new RecyclorItemBean(1,"物品一","http://img4q.duitang.com/uploads/item/201411/20/20141120132318_3eAuc.thumb.700_0.jpeg"),
new RecyclorItemBean(2,"物品二","http://heilongjiang.sinaimg.cn/2015/0326/U10061P1274DT20150326104659.jpg"),
new RecyclorItemBean(3,"物品三","http://hiphotos.baidu.com/%CC%EC%C9%BD%B6%FE%CF%C0%B5%C4%D0%A1%CE%DD/pic/item/70c553e736d12f2e5b0614d64fc2d5628535682a.jpg"));
list.add(0,recyclorBean);
handler.sendMessage(msg);
}
});
try {
Thread.sleep(3000);
thread.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
四.handler异步处理 回到主线程
public static Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
homeCategoryAdapter.notifyItemRangeChanged(0,1); //更新adapter,更新后的adapter的位置
recyclerView.scrollToPosition(0); //重新锁定recyclorview的位置
swipeRefreshLayout.setRefreshing(false); //刷新完了直接关闭
}
}
};