android 控件 下拉刷新 SwipeRefreshLayout

来源:互联网 发布:淘宝小号信誉查询 编辑:程序博客网 时间:2024/04/30 10:14

 SwipeRefreshLayout字面意思就是下拉刷新的布局,继承自ViewGroup,在support v4兼容包下(android.support.v4.widget.SwipeRefreshLayout),但必须把你的support library的版本升级到19.1。

这是google推出的官方下拉刷新组件。

xml布局文件

This layout should be made the parent of the view that will be refreshed as a result of the gesture and can only support one direct child.

只要在需要刷新的控件最外层加上SwipeRefreshLayout,然后他的child首先是可滚动的view,如ScrollView或者ListView。

XML文件
<android.support.v4.widget.SwipeRefreshLayout     xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:id="@+id/swipeLayout" >         <ListView         android:id="@+id/mylist"        android:layout_width="match_parent"        android:layout_height="wrap_content"/>    </android.support.v4.widget.SwipeRefreshLayout>


代码

tv = (TextView)findViewById(R.id.textView1);
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);  
swipeLayout.setOnRefreshListener(this);  

//加载颜色是循环播放的,只要没有完成刷新就会一直循环,color1>color2>color3>color4  
//setColorScheme()已经弃用,使用setColorSchemeResources()来设置颜色。
swipeLayout.setColorScheme(android.R.color.white, android.R.color.holo_green_light,  
android.R.color.holo_orange_light, android.R.color.holo_red_light);  
  
public void onRefresh() { 

tv.setText("正在刷新");

new Handler().postDelayed(new Runnable() {  
public void run() {  

swipeLayout.setRefreshing(false);  

tv.setText("刷新完成");                        
}  
}, 3000); }  

setOnRefreshListener(OnRefreshListener): 为布局添加一个ListenerisRefreshing(): 检查是否处于刷新状态setColorScheme(): 设置进度条的颜色主题,最多能设置四种,现在是setColorSchemeResourcessetProgressBackgroundColor(int colorRes):设置进度圈的背景色。setSize(int size):设置进度圈的大小,只有两个值:DEFAULT、LARGE

如果需要一个刷新的动画,setRefreshing(true), 停: setRefreshing(false)

如果要禁用刷新动画和手势响应,ssetEnable(false),  恢复setEnable(true)

在某些情况下,不仅有ListView可能还有其他的元素。
这种情况有些复杂,如果我们向上滚动在ListView中项目,一切都如预期那样显示。但如果向下滚动,刷新过程开始列表项并不滚动。在这种情况下,我们可以使用一个小技巧,可以通过setEnabled(false)禁止使用刷新通知,当Listview中第一个项可见时而再启用它:
lView.setOnScrollListener(new AbsListView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {}
 
    @Override
    public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, 
int totalItemCount) {
            if (firstVisibleItem == 0)
                swipeView.setEnabled(true);
            else
                swipeView.setEnabled(false);
        }
    });


0 0