listview,scrollview,recyclerview等如果碰到更新比较快的数据,没有下拉刷新就显得特别呆板了。于是google就推出了swipeRefreshLayout 这个简单却又实用的组件(知乎APP就是用的这个哦)。
笔者博文还是主要给新手提供一个简单的demo学习,效果如下:
![](https://box.kancloud.cn/2016-03-01_56d5568df0ac7.jpg)
![](https://box.kancloud.cn/2016-03-01_56d5568e14bac.jpg)
![](https://box.kancloud.cn/2016-03-01_56d5568e2d6f0.jpg)
代码特别简单,就不多加描述了。
MainActivity:
~~~
package com.example.swiperefreshlayouttest;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener{
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private ArrayAdapter<String> adapter;
private List<String> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
data = new ArrayList<String>();
for (int i = 0; i < 20; i++) {
data.add("当前的item为 " + i);
}
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
//在刷新等待时,滚动条颜色的变化
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light, android.R.color.holo_orange_light);
//给swipeRefreshLayout绑定刷新监听
swipeRefreshLayout.setOnRefreshListener(this);
}
@Override
public void onRefresh() {
//设置2.5秒的时间来执行以下事件
new Handler().postDelayed(new Runnable() {
public void run() {
data.add(0, "刷新后新增的item");
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}, 2500);
}
}
~~~
activity_main:
~~~
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:footerDividersEnabled="false" />
</android.support.v4.widget.SwipeRefreshLayout>
~~~
- 前言
- android Nine-Patch的使用(制作聊天界面必学)
- android 图片文字轮播效果(图片和文字自动滚动)
- LinearLayout布局中如何让控件置底
- viewpager+将activity转化成view 做主界面(可点击可滑动,超容易理解的demo)
- android swipeRefreshLayout 下拉刷新 google官方组件
- android 自定义AlertDialog 与Activity相互传递数据
- android 简单地设置Activity界面的跳转动画
- android XML动画初步解析(activity界面之间跳转demo)
- android selector设置button点击效果(详细)以及常见问题
- android 用java动态设置布局(增添删除修改布局)