Android SwipeRefreshLayout教程
SwipeRefreshLayout也是一种下拉刷新控件,不同的它的刷新状态效果和传统的PuulToRefresh完全不一样,具体效果可以参考Google Now的刷新效果,见下图:
SwipeRefreshLayout已经被放到了sdk中,在version 19.1之后SwipeRefreshLayout 被放到support v4中。
SwipeRefreshLayout控件值允许有一个子元素:我们想滑动刷新的对象。它使用Listener机制来告之持有SwipeRefreshLayout的组建某个事件发生了,也就是说假如是activity持有SwipeRefreshLayout,那么activity就必须实现一个接口来接收通知,这个接口中需要实现的主要是onRefresh()方法。
除此之外SwipeRefreshLayout还提供了一些公共方法:
setOnRefreshListener(OnRefreshListener): 为布局添加一个Listener
setRefreshing(boolean): 显示或隐藏刷新进度条
isRefreshing(): 检查是否处于刷新状态
setColorScheme(): 设置进度条的颜色主题,最多能设置四种
如何使用
我将通过一个产生随机数字的demo来讲解如何使用SwipeRefreshLayout,刷新一次就产生随机数字。
一般SwipeRefreshLayout作为根节点被放入布局文件中:
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:id="@+id/swipe">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Random number:"
android:id="@+id/lbl"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/rndNum"
android:layout_toRightOf="@id/lbl"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/lbl"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Swipe to Refresh"
style="@android:style/TextAppearance.Medium"/>
</RelativeLayout>
</ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
上面的代码中SwipeRefreshLayout只有一个为scrollView的子元素。接下来activity中:
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
final TextView rndNum = (TextView) findViewById(R.id.rndNum);
swipeView.setColorScheme(android.R.color.holo_blue_dark, android.R.color.holo_blue_light, android.R.color.holo_green_light, android.R.color.holo_green_light);
swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeView.setRefreshing(true);
Log.d("Swipe", "Refreshing Number");
( new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
swipeView.setRefreshing(false);
double f = Math.random();
rndNum.setText(String.valueOf(f));
}
}, 3000);
}
});
}
....
所有的代码都在onCreate中了。
上面的代码很简单,只需要给SwipeRefreshLayout添加一个listener,值得说明的是setColorScheme方法是设置刷新进度条的颜色,最多只能设置4种循环显示,默认第一个是随用户手势加载的颜色进度条。
源码
github上有SwipeRefreshLayout的例子源码,地址在:SwipeRefreshLayoutDemo