android开发笔记之SwipeRefreshLayout

SwipeRefreshLayout简介

SwipeRefrshLayout是Google官方更新的一个控件,可以实现下拉刷新的效果,该控件集成自ViewGroup在support-v4兼容包下.

在android源码中,主要是在联系人界面刷新联系人数据:

packages/apps/Contacts/src/com/android/contacts/list/DefaultContactBrowseListFragment.java

和文件夹应用的文件显示界面:

packages/apps/DocumentsUI/src/com/android/documentsui/dirlist/DirectoryFragment.java

Demo

主要实现下拉SwipeRefrshLayout控件,刷新listview控件的数据.

(1) 布局文件—activity_main.xml




    

    
        
    


(2)实现逻辑

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{

    private final static String TAG = "MainActivity";

    private SwipeRefreshLayout swipeRefreshLayout;
    private TextView textView;
    private ListView listview;
    private ArrayAdapter adapter;
    private List data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.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);

        textView = (TextView) findViewById(R.id.textView);
        listview = (ListView) findViewById(R.id.listView);
        data = new ArrayList();
        for (int i = 0; i < 5; i++) {
            data.add("初始的item为:" + i);
        }
        adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, data);
        listview.setAdapter(adapter);
    }

    public void showLoading() {
        textView.setText("正在刷新,请等待");
    }

    public void hideLoading() {
        textView.setText("刷新完毕!");
        swipeRefreshLayout.setVisibility(View.VISIBLE);
        swipeRefreshLayout.setRefreshing(false); // close refresh animator
    }

    @Override
    public void onRefresh() {
        Log.i(TAG,"onRefresh()");
        showLoading();
        final Random random = new Random();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                hideLoading();
                int min=1;
                int max=20;
                Random random = new Random();
                int num = random.nextInt(max)%(max-min+1) + min;
                data.clear();
                for(int i=0;i < num;i++){
                    data.add("刷新后新增的item:"+i);
                }
                adapter.notifyDataSetChanged();
            }
        }, 5000);
    }

}

参考资料

1.Android零基础入门|SwipeRefreshLayout下拉刷新
http://www.sohu.com/a/195607552_619467
2.SwipeRefreshLayout + RecyclerView 实现 上拉刷新 和 下拉刷新
https://www.cnblogs.com/liunanjava/p/5860024.html

你可能感兴趣的:(android开发笔记)