网上的下拉刷新控件有很多,比如常用的PullToRefresh、XListView等,这篇文章我们来学习Android 官方的下拉刷新SwipeRefreshLayout。SwipeRefreshLayout是v4包中的,注意要把Support library的版本升级到19.1以上。下面我们来看下怎样实现。
一、布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.huang.loadimage.MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="300dp" />
</ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
二、主要代码
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
//设置颜色
swipeRefreshLayout
.setColorSchemeResources(android.R.color.holo_red_light);
//设置监听
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
public void onRefresh() {
//将setRefreshing设置为true
swipeRefreshLayout.setRefreshing(true);
}
});
停止刷新:
swipeRefreshLayout.setRefreshing(true);
效果图: