前天Google官方終於出了Android刷新控件——SwipeRefreshLayout。
使用前先需要將android.support.v4.jar升級到19.1。升級后,可能會出現SDK版本與Android ADT Bundle
版本不一致從而導致ADT Bundle無法使用的情況。
解決方法可以參照上文:升級SDK Manager后引起的Android Developer ToolKit版本不一致問題。
SwipeRefreshLayout官方文檔網址:http://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html。
其中有針對本下拉刷新控件詳細的說明。重點的是要實現內部接口SwipeRefreshLayout.OnRefreshListener,並針對SwipeRefreshLayout控件
這是刷新的監聽器(通過setOnRefreshListener方法)。同時也提供了對事件的處理以及View的繪制處理等。
簡單demo如下:
Java代碼:
1 package com.corn.swiperefreshlayoutdemo; 2
3 import com.storm.swiperefreshlayoutdemo.R; 4
5 import android.app.Activity; 6 import android.os.Bundle; 7 import android.support.v4.widget.SwipeRefreshLayout; 8 import android.util.Log; 9
10 public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener { 11 private SwipeRefreshLayout swipeLayout; 12
13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_main); 16
17 swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); 18 swipeLayout.setOnRefreshListener(this); 19 swipeLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, 20 android.R.color.holo_red_light); 21 } 22
23 public void onRefresh() { 24 Log.w("test", "in onRefresh"); 25 } 26 }
Xml布局文件:
1 <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 android:id="@+id/swipe_container"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent" >
5
6 <ScrollView 7 android:layout_width="match_parent"
8 android:layout_height="match_parent" >
9
10 <TextView 11 android:layout_width="match_parent"
12 android:layout_height="wrap_content"
13 android:layout_marginTop="16dp"
14 android:gravity="center"
15 android:text="@string/hello_world" />
16 </ScrollView>
17
18 </android.support.v4.widget.SwipeRefreshLayout>