Android官方下拉刷新控件 SwipeRefreshLayout

今天在Google+上看到了SwipeRefreshLayout这个名词,遂搜索了下,发现居然是刚刚google更新sdk新增长的一个widget,因而赶忙抢先体验学习下。android

SwipeRefreshLayout

SwipeRefreshLayout字面意思就是下拉刷新的布局,继承自ViewGroup,在support v4兼容包下,但必须把你的support library的版本升级到19.1。 提到下拉刷新你们必定对ActionBarPullToRefresh比较熟悉,而现在google推出了更官方的下拉刷新组件,这无疑是对开发者来讲比较好的消息。利用这个组件能够很方便的实现Google Now的刷新效果,见下图:git

主要方法

  • setOnRefreshListener(OnRefreshListener): 为布局添加一个Listenergithub

  • setRefreshing(boolean): 显示或隐藏刷新进度条ide

  • isRefreshing(): 检查是否处于刷新状态布局

  • setColorScheme(): 设置进度条的颜色主题,最多能设置四种post

xml布局文件

布局文件很简单,只须要在最外层加上SwipeRefreshLayout,而后他的child是可滚动的view便可,如ScrollView或者ListView。如:学习

<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <TextView
            android:text="@string/hello_world"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:gravity="center"/>
    </ScrollView>
 </android.support.v4.widget.SwipeRefreshLayout>

Activity代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 
    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeLayout.setOnRefreshListener(this);
    swipeLayout.setColorScheme(android.R.color.holo_blue_bright, 
            android.R.color.holo_green_light, 
            android.R.color.holo_orange_light, 
            android.R.color.holo_red_light);}
 public void onRefresh() {
    new Handler().postDelayed(new Runnable() {
        @Override public void run() {
            swipeLayout.setRefreshing(false);
        }
    }, 5000);}

上面的代码很简单,只须要给SwipeRefreshLayout添加一个listener,值得说明的是setColorScheme方法是设置刷新进度条的颜色,最多只能设置4种循环显示,默认第一个是随用户手势加载的颜色进度条。this

源码

写了的小demo在github上,地址在:SwipeRefreshLayoutDemogoogle

总结

google在不断完善本身的sdk,推出愈来愈多的组件,其目的是让开发更简单,设计上更统一,这多是google将来的方向,无论怎样,这对开发者来讲无疑是很是好的消息。spa

相关文章
相关标签/搜索