Android SwipeRefreshLayout

SwipeRefreshLayout字面意思就是下拉刷新的佈局,繼承自ViewGroup,在support v4兼容包下,但必須把你的support library的版本升級到19.1。 提到下拉刷新你們必定對ActionBarPullToRefresh比較熟悉,而現在google推出了更官方的下拉刷新組件,這無疑是對開發者來講比較好的消息。利用這個組件能夠很方便的實現Google Now的刷新效果,見下圖:
html

主要方法

  • setOnRefreshListener(OnRefreshListener): 爲佈局添加一個Listenerandroid

  • setRefreshing(boolean): 顯示或隱藏刷新進度條git

  • isRefreshing(): 檢查是否處於刷新狀態github

  • setColorScheme(): 設置進度條的顏色主題,最多能設置四種ide

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種循環顯示,默認第一個是隨用戶手勢加載的顏色進度條。post

源碼

寫了的小demo在github上,地址在:SwipeRefreshLayoutDemothis

總結

google在不斷完善本身的sdk,推出愈來愈多的組件,其目的是讓開發更簡單,設計上更統一,這多是google將來的方向,無論怎樣,這對開發者來講無疑是很是好的消息。google

相關文章
相關標籤/搜索