swipeRefreshLayoutAndroidAndroid开发经验谈

SwipeRefreshLayout的使用(下拉刷新)

2016-08-14  本文已影响5531人  JC_Hou
在布局中导入

SwipeRefreshLayout在V4包下,作为一个布局,可以在内部嵌套如listview,recycleView等,这里作为例子嵌套了一个listview

  <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ListView
            android:id="@+id/list_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></ListView>
    </android.support.v4.widget.SwipeRefreshLayout>
在代码中使用
public class SwipeActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
    //声明控件
    private SwipeRefreshLayout swiper;
    private ListView mListView;
    //声明并初始化ListView的数据源
    private List<String> list = new ArrayList<>();
    //声明ListView的适配器
    private ArrayAdapter adapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.swipe_layout);
        //初始化SwipeRefreshLayout
        swiper = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        //为SwipeRefreshLayout设置监听事件
        swiper.setOnRefreshListener(this);                           
        //为SwipeRefreshLayout设置刷新时的颜色变化,最多可以设置4种
        swiper.setColorSchemeResources(android.R.color.holo_blue_bright, 
            android.R.color.holo_green_light, 
            android.R.color.holo_orange_light, 
            android.R.color.holo_red_light);
        //初始化ListView
        mListView = (ListView) findViewById(R.id.list_view);
        //初始化适配器
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getData());
        //设置适配器
        mListView.setAdapter(adapter);
    }
    //增加数据
    private List<String> getData() {
        list.add("hello");
        list.add("this is johnsonHou");
        list.add("an android rookie developer");
        list.add("love android");
        return list;
    }
    //实现OnRefreshListener 的onRefresh()方法
    @Override
    public void onRefresh() {
        //刷新
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //结束后停止刷新
                swiper.setRefreshing(false);
            }
        }, 3000);
//  一般会从网络获取数据
//        new Handler().post(new Runnable() {
//            @Override
//            public void run() {
//                获取数据
//                refreshData();
//                swiper.setRefreshing(false);
//            }
//        });
    }
//简单示例,手动添加数据
    private void refreshData() {
        list.add(0, String.valueOf((int) (Math.random() * 10)));
        adapter.notifyDataSetChanged();
    }
}
效果图如下
SwipeRefresh.gif
上一篇下一篇

猜你喜欢

热点阅读