前天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>