本文共 3143 字,大约阅读时间需要 10 分钟。
PullToRefreshListView实现上拉和下拉刷新有两个步骤:
1、设置刷新方式
pullToRefreshView.setMode(PullToRefreshBase.Mode.BOTH);//两端刷新 pullToRefreshView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);//上拉刷新 pullToRefreshView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);//下拉刷新
2、如果是上拉刷新或者下拉刷新需要实现OnRefreshListener接口;如果是两端刷新,则setOnRefreshListener需要实现OnRefreshListener2接口
两端刷新实现:
pullToRefreshView = (PullToRefreshListView) view.findViewById(R.id.pull_to_refresh_listview); pullToRefreshView.setMode(PullToRefreshBase.Mode.BOTH);//两端刷新// pullToRefreshView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);//上拉刷新// pullToRefreshView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);//下拉刷新 pullToRefreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() { @Override public void onPullDownToRefresh(PullToRefreshBase refreshView) { refreshType = REFRESH_TYPE_DOWN; refreshView.getLoadingLayoutProxy().setRefreshingLabel("正在加载"); refreshView.getLoadingLayoutProxy().setPullLabel("下拉加载更多"); refreshView.getLoadingLayoutProxy().setReleaseLabel("释放开始加载");// refreshView.getLoadingLayoutProxy().setLastUpdatedLabel("最后加载时间:"); // Do work to refresh the list here. new GetDataTask().execute(); } @Override public void onPullUpToRefresh(PullToRefreshBase refreshView) { refreshType = REFRESH_TYPE_UP; refreshView.getLoadingLayoutProxy().setRefreshingLabel("正在加载"); refreshView.getLoadingLayoutProxy().setPullLabel("上拉加载更多"); refreshView.getLoadingLayoutProxy().setReleaseLabel("释放开始加载");// refreshView.getLoadingLayoutProxy().setLastUpdatedLabel("最后加载时间:"); // Do work to refresh the list here. new GetDataTask().execute(); } });
AsyncTask实现异步加载
private class GetDataTask extends AsyncTask{ @Override protected String[] doInBackground(Void... params) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } return new String[0]; } @Override protected void onPostExecute(String[] result) { // Call onRefreshComplete when the list has been refreshed. pullToRefreshView.onRefreshComplete(); if(REFRESH_TYPE_DOWN == refreshType){ Article article = new Article(); article.setTitle("下拉刷新添加title"); adapter.insert(article,0);//adapter是一个LinkedList }else if(REFRESH_TYPE_UP == refreshType){ Article article = new Article(); article.setTitle("上拉刷新添加title"); adapter.add(article); } super.onPostExecute(result); } }
如果想实现更丰富的效果可修改布局文件参数,如: