网上关于下拉刷新的文章也不少,但是依赖的库文件太重了。恰好发现了官方的下拉刷新库,而且效果还是不错的:简洁美观,使用方便。
这是最基本的下拉刷新例子-可扩展
看图啦
Step-one:下拉刷新布局文件
<?xml version="1.0"encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
<android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
Step-two:java处理文件
packagecom.samego.alic.purgepulltorefresh;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.support.v4.widget.SwipeRefreshLayout;
importandroid.support.v7.app.AppCompatActivity;
importandroid.support.v7.widget.Toolbar;
importandroid.widget.ArrayAdapter;
importandroid.widget.ListView;
public classMainActivityextendsAppCompatActivity {
privateSwipeRefreshLayoutmSwipeLayout;
privateListViewlistView;
privateArrayAdapteradapter;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//实例化刷新布局
mSwipeLayout= (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
//listView主内容
listView= (ListView) findViewById(R.id.listView);
adapter=newArrayAdapter(this,android.R.layout.simple_list_item_1);
adapter.add("Alic-one");
adapter.add("Alic-two");
adapter.add("Alic-three");
listView.setAdapter(adapter);
//设置刷新时动画的颜色,可以设置4个
mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_light,android.R.color.holo_red_light,android.R.color.holo_orange_light,android.R.color.holo_green_light);
//handler用来更新UI的 注意需要定义自己的Handler类-防泄露
finalHandler handler =newHandler(){
@Override
public voidhandleMessage(Message msg) {
//TODO
adapter.add("Alic-Refresh");
super.handleMessage(msg);
//取消更新的动画
mSwipeLayout.setRefreshing(false);
}
};
//设置监听器
mSwipeLayout.setOnRefreshListener(newSwipeRefreshLayout.OnRefreshListener() {
@Override
//正在更新的时候执行什么代码
public voidonRefresh() {
newThread(newRunnable() {
@Override
public voidrun() {
//模拟在服务器获取数据等待一秒
try{
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
//发消息给handler更新UI
Message message =newMessage();
handler.sendMessage(message);
}
}).start();
}
});
}
}