下拉刷新是使用SwipeRefreshLayout来实现的,我们只要把想要实现下拉刷新功能的控件放置到SwipeRefreshLayout中,就可以迅速让这个控件支持下拉刷新。
为了简单起见,下面我将通过ListView实现下拉刷新功能,效果图如下:
可以看到此处我给ListView添加了一个下拉刷新,还给下拉刷新设置了一个监听事件,下拉刷新更改ListView子项中的内容。
布局代码如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ListActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/list_swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</android.support.v4.widget.SwipeRefreshLayout>
</android.support.constraint.ConstraintLayout>
java代码如下:
public class ListActivity extends AppCompatActivity {
private ListView listView;
private SwipeRefreshLayout swipeRefreshLayout;
private ArrayAdapter<String> adapter;
private String[] data = {"草果", "梨子", "草莓", "芒果", "香蕉"};
private String[] sourceData = new String[50];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = findViewById(R.id.list_view);
swipeRefreshLayout = findViewById(R.id.list_swipe);
// 初始化数据
initData();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, sourceData);
listView.setAdapter(adapter);
// 设置刷新进度条颜色
swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
// 设置刷新监听事件
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refresh();
}
});
}
private void refresh() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
// 对sourceData数组中的值进行更改
initData();
// 刷新数据
adapter.notifyDataSetChanged();
// 刷新事件结束,隐藏进度条
swipeRefreshLayout.setRefreshing(false);
}
});
}
}).start();
}
private void initData() {
for (int i = 0; i < 50; i++) {
Random random = new Random();
// index为一个[0,data.length)区间的一个随机数
int index = random.nextInt(data.length);
// 将data数组中的数据随机赋值给sourceData数组
sourceData[i] = data[index];
}
}
}