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<ListView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> 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<ListView> 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<Void, Void, String[]> { @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); } }
如果想实现更丰富的效果可修改布局文件参数,如:
<!-- ptr:ptrDrawable="@drawable/default_ptr_flip" ptr:ptrAnimationStyle="flip" flip:翻转 rotate:旋转 --> <!-- ptr:ptrShowIndicator="true" 右上角 右下角出现箭头--> <com.handmark.pulltorefresh.library.PullToRefreshListView android:id="@+id/pull_to_refresh_listview" android:layout_height="fill_parent" android:layout_width="fill_parent" ptr:ptrShowIndicator="true" android:background="#CCC" />
时间: 2024-09-30 02:47:53