網上的下拉刷新控件有很多,比如常用的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);
效果圖: