Welcome 微信登录

首页 / 移动开发 / Android / Android下拉刷新官方版

网上关于下拉刷新的文章也不少,不过都太长了。恰好发现了官方的下拉刷新库,而且效果还是不错的,简洁美观,用得也挺方便。
下面是效果图:
我的好友原来是空的,刷新后多了两个。


使用还是挺方便的,在布局文件中加入SwipeRefreshLayout ,这个就是下拉刷新的布局。
我在SwipeRefreshLayout的里面还加入了一个ListView 因为我主要用下拉刷新更新了listView里面的内容 。
布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" ><android.support.v4.widget.SwipeRefreshLayout android:id="@+id/id_swipe_ly" android:layout_width="match_parent" android:layout_height="match_parent" ><ListView android:id="@+id/id_listview" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView> </android.support.v4.widget.SwipeRefreshLayout></RelativeLayout> 
代码写到这里后,只要在主界面向下滑动到顶部,就会出现下拉刷新了。
然后我们要实例化这个下拉刷新布局,设置好它在刷新时要干什么,完成刷新后,旋转的图标要消失。

mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.haoyouliebiaoshuaxin);//实例化              //handler 用来更新UI的haoyouhandler = new Handler(){@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);//要做的事Item i1 = new Item();i1.name = "呵呵";i1.account = 25566;haoyou.add(i1);Item i2 = new Item();i2.name = "哈哈";i2.account = 25577;haoyou.add(i2);haoyouadpter = new liebiaoAdapter(MainActivity.this, R.layout.liebiao, haoyou);haoyoulist.setAdapter(haoyouadpter);                                                        //取消更新的动画mSwipeLayout.setRefreshing(false);}};                                          //设置监听器mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {@Override                //正在更新的时候执行什么代码public void onRefresh() {new Thread(new Runnable() {@Overridepublic void run() {//等待一秒try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}                          //发消息给handler更新UIMessage ok = new Message();haoyouhandler.sendMessage(ok);}}).start();
我是在监听器的onRefresh函数中,等待一秒,然后发消息给Handler去更新UI,更新完后再取消更新。
以上就是本文的全部内容,希望对大家的学习有所帮助。