安卓PullToRefresh自动下拉加载刷新实现

昨天,测试人员提了一个Bug,说是只要来回的点击同一个Tab按钮,加载的数据就会重复,检查代码检查了好长时间也没有发现有啥问题,于是就打断点调试,发现本来是执行的pullToRefreshListView.setRefreshing(); 自以为是执行的刷新操作(其实也就是刷新操作,只不过上拉是刷新,下拉也是刷新,我们做的时候是把上拉刷新改成加载更多了),其实该控件并不能判断出来目前执行的操作是下拉刷新还是上拉加载更多,这就需要自定义一个布尔变量isAutoRefresh,通过它来识别是不是下拉刷新的动作,下面给出实现的源码:

public class MyTopicFragment extends Fragment implements MyTopicObserver,
		OnItemClickListener, OnRefreshListener<ListView>,
		OnLastItemVisibleListener {

	private int mType = 0;
	private PullToRefreshListView pullToRefreshListView;
	private ListView actualListView;
	private MyTopicListAdapter myTopicListAdapter;
	private Context mContext;
	private MyTopicLogic logic;

	private int currentPageCount = 0; // 记录当前为第几页
	private int totalPageCount; // 记录总页数
	private boolean isRefreshAction;// 标志是否是下拉刷新
	private MyTopicEntity mMyTopicEntity;

	private LinearLayout promptView;// 无任何话题的时候显示的提示语

	private LinearLayout mLoadingHint = null;
	private LinearLayout mAfterLodingHint = null;
	private ImageView mHintImage = null;
	private TextView mHintTxt = null;

	private boolean isAutoRefresh = false;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Bundle args = this.getArguments();
		mType = args.getInt("type");
		mContext = this.getActivity();
		logic = new MyTopicLogic();
		logic.addObserver(this);
		View rootView = inflater.inflate(
				R.layout.fragment_pulltorefresh_listview, container, false);
		initialize(rootView);
		return rootView;
	}

	private void initialize(View rootView) {
		pullToRefreshListView = (PullToRefreshListView) rootView
				.findViewById(R.id.fragment_pulltorefresh_listview);
		myTopicListAdapter = new MyTopicListAdapter();
		actualListView = pullToRefreshListView.getRefreshableView();
		registerForContextMenu(actualListView);
		actualListView.setAdapter(myTopicListAdapter);

		pullToRefreshListView.setMode(Mode.BOTH);
		pullToRefreshListView.getLoadingLayoutProxy(false, true).setPullLabel(
				getString(R.string.poll_refresh_down_loadmore));
		pullToRefreshListView.getLoadingLayoutProxy(false, true)
				.setRefreshingLabel(
						getString(R.string.poll_refresh_down_refreshing));
		pullToRefreshListView.getLoadingLayoutProxy(false, true)
				.setReleaseLabel(getString(R.string.poll_refresh_down_release));
		pullToRefreshListView.getLoadingLayoutProxy(false, true)
				.setLastUpdatedLabel("");

		pullToRefreshListView.setOnRefreshListener(this);
		pullToRefreshListView.setOnLastItemVisibleListener(this);
		pullToRefreshListView.setOnItemClickListener(this);

		mMyTopicEntity = HealthApplication.mAPPCache.getMyTopic(mType);
		if (mMyTopicEntity != null && mMyTopicEntity.getData() != null) {
			myTopicListAdapter.refresh(mMyTopicEntity.getData().getData());
			currentPageCount = 1;
		}

		promptView = (LinearLayout) LayoutInflater.from(mContext).inflate(
				R.layout.net_request_prompt, null);
		pullToRefreshListView.setEmptyView(promptView);

		if (mType == 1) {// 默认全部显示我发布的话题
			mHandler.sendEmptyMessageDelayed(1, 500);
			//logic.getMyTopic(10, 1, mType, "time");
		}/*
		 * else if(mType == 2){ logic.getMyTopic(10, 1, mType, "time"); }else
		 * if(mType == 3){ logic.getMyTopic(10, 1, mType, "time"); }
		 */
		// mType = 1;//设置为1,只要是进入我发布的,还没有点击过我回复的和我收藏的,刷新操作将会执行我发布的话题
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				//pullToRefreshListView.setCurrentModeRefreash();
				isAutoRefresh = true;
				pullToRefreshListView.setRefreshing();
				break;

			default:
				break;
			}
		}

	};

	@Override
	public void onPause() {
		logic.removeObserver(this);
		super.onPause();
	}

	@Override
	public void onResume() {
		if (logic.getObservers().size() == 0) {
			logic.addObserver(this);
		}
		super.onResume();
	}

	@Override
	public void onItemClick(AdapterView<?> listView, View itemView,
			int position, long itemViewId) {
		MyTopicDetail item = (MyTopicDetail) myTopicListAdapter
				.getItem(position - 1);
		Intent intent = new Intent(mContext, TopicDetailActivity.class);
		intent.putExtra("topicId", item.getId());
		startActivityForResult(intent, 18);

	}

	@Override
	public void onLastItemVisible() {
		if (pullToRefreshListView.getMode() == Mode.PULL_FROM_START) {
			// Toast.makeText(mContext, "没有更多话题了", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		if (refreshView.isHeaderShown() || isAutoRefresh) {
			isAutoRefresh = false;
			isRefreshAction = true;
			logic.getMyTopic(10, 1, mType, "time");
		} else {
			isRefreshAction = false;
			logic.getMyTopic(10, currentPageCount + 1, mType, "time");
		}
	}

	public void refresh(int type) {
		isRefreshAction = true;
		mType = type;
		mHandler.sendEmptyMessageDelayed(1, 500);
		//logic.getMyTopic(10, 1, mType, "time");
	}

	private class MyTopicListAdapter extends BaseAdapter {

		private ArrayList<MyTopicDetail> mList;

		public MyTopicListAdapter() {
			mList = new ArrayList<MyTopicDetail>();
		}

		public void refresh(ArrayList<MyTopicDetail> arrayList) {
			mList.clear();
			mList = arrayList;
			notifyDataSetChanged();
		}

		public void add(ArrayList<MyTopicDetail> arrayList) {
			mList.addAll(arrayList);
			notifyDataSetChanged();
		}

		public void clear() {
			mList.clear();
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				LayoutInflater inflater = LayoutInflater.from(mContext);
				convertView = inflater
						.inflate(R.layout.mytopic_list_item, null);
				viewHolder = new ViewHolder();
				viewHolder.topicName = (TextView) convertView
						.findViewById(R.id.tv_topic_name);
				viewHolder.topicContent = (TextView) convertView
						.findViewById(R.id.tv_topic_content);
				viewHolder.coloumnName = (TextView) convertView
						.findViewById(R.id.column);
				viewHolder.topicTime = (TextView) convertView
						.findViewById(R.id.sendtime);
				viewHolder.topicGoodCnt = (TextView) convertView
						.findViewById(R.id.tv_good);
				viewHolder.topicReplyCnt = (TextView) convertView
						.findViewById(R.id.tv_replay);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			MyTopicDetail item = (MyTopicDetail) getItem(position);
			if (item.getTitle().length() > 30) {
				String str = item.getTitle().substring(0, 30);
				viewHolder.topicName.setText(str + "...");
			} else {
				viewHolder.topicName.setText(item.getTitle());
			}
			if (item.getContent().length() > 80) {
				String temp = (item.getContent().substring(0, 80));
				viewHolder.topicContent.setText(temp + "...");
			} else {
				viewHolder.topicContent.setText(item.getContent());
			}
			if (item.getSectname().length() > 8) {
				String temp = (item.getSectname().substring(0, 6));
				viewHolder.coloumnName.setText(temp + "...");
			} else {
				viewHolder.coloumnName.setText(item.getSectname());
			}
			viewHolder.topicTime.setText(item.getCreate_time());
			viewHolder.topicGoodCnt.setText(item.getGoodcnt() + "");
			viewHolder.topicReplyCnt.setText(item.getDiscusscnt() + "");
			return convertView;
		}

		private class ViewHolder {
			public TextView topicName;// 话题名称
			public TextView topicContent;// 话题内容
			public TextView coloumnName;// 专栏名字
			public TextView topicTime;// 话题时间
			public TextView topicGoodCnt;// 赞的个数
			public TextView topicReplyCnt;// 回复的个数
		}
	}

	@Override
	public void onGetMyTopicSuccess(MyTopicEntity result) {

		pullToRefreshListView.onRefreshComplete();

		if (result.getData() == null) {
			showPromptView(false, getString(R.string.topic_nodata), 1);
			myTopicListAdapter.clear();
			pullToRefreshListView.setMode(Mode.BOTH);
			currentPageCount = 0;
			HealthApplication.mAPPCache.setMyTopic(mType, "");
			showPromptView(false, getResources().getString(R.string.temp_no_data), 1);
		}

		totalPageCount = result.getData().getPagecount();
		if (isRefreshAction) {
			myTopicListAdapter.refresh(result.getData().getData());
			currentPageCount = 1;
			String label = DateUtils.formatDateTime(mContext,
					System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
							| DateUtils.FORMAT_SHOW_DATE
							| DateUtils.FORMAT_ABBREV_ALL);
			pullToRefreshListView.getLoadingLayoutProxy(true, false)
					.setLastUpdatedLabel(label);
			if (1 == totalPageCount) {
				pullToRefreshListView.setMode(Mode.PULL_FROM_START);
			} else {
				pullToRefreshListView.setMode(Mode.BOTH);
			}
		} else {
			myTopicListAdapter.add(result.getData().getData());
			currentPageCount++;
			if (currentPageCount >= totalPageCount) {
				pullToRefreshListView.setMode(Mode.PULL_FROM_START);
			}
		}
	}

	@Override
	public void onGetMyTopicFailed(int errorCode, String msg) {

		pullToRefreshListView.onRefreshComplete();
		if(errorCode == 17){
			showPromptView(false, getString(R.string.topic_nodata), 1);
			myTopicListAdapter.clear();
			pullToRefreshListView.setMode(Mode.BOTH);
			currentPageCount = 0;
			HealthApplication.mAPPCache.setMyTopic(mType, "");
			showPromptView(false, getResources().getString(R.string.temp_no_data), 1);
		}else {
			HaloToast.show(mContext, msg);
			showPromptView(false, getResources().getString(R.string.req_fail_click_refresh), 2);
		}
	}

	/**
	 * 加载及加载之后的提示语
	 *
	 * @param isProgressShow
	 *            是否显示进度框
	 * @param text
	 *            显示的文字
	 * @param type
	 *            控制显示哪一个布局:0标识显示正在加载,1标识请求成功,但是暂无数据,2标识请求失败
	 */
	private void showPromptView(boolean isProgressShow, String text, int type) {
		mAfterLodingHint = (LinearLayout) promptView
				.findViewById(R.id.after_loding_hint_layout);
		mLoadingHint = (LinearLayout) promptView.findViewById(R.id.loding_hint);
		mHintImage = (ImageView) promptView.findViewById(R.id.hint_image);
		mHintTxt = (TextView) promptView.findViewById(R.id.hint_txt);

		View progressBar = promptView
				.findViewById(R.id.net_request_prompt_progressBar);
		TextView promptTextView = (TextView) promptView
				.findViewById(R.id.net_request_prompt_textView);
		promptView.setClickable(false);
		if (type == 0) {
			mLoadingHint.setVisibility(View.VISIBLE);
			mAfterLodingHint.setVisibility(View.GONE);
			if (isProgressShow) {
				progressBar.setVisibility(View.VISIBLE);
			} else {
				progressBar.setVisibility(View.GONE);
			}
			promptTextView.setText(text);
		} else if (type == 1) {
			mLoadingHint.setVisibility(View.GONE);
			mHintImage.setClickable(false);
			mHintImage.setImageResource(R.drawable.no_data);
			mHintTxt.setText(text);
			mAfterLodingHint.setVisibility(View.VISIBLE);
		} else if (type == 2) {
			promptView.setClickable(true);
			mLoadingHint.setVisibility(View.GONE);
			mHintImage.setImageResource(R.drawable.click_refresh_selector);
			mHintTxt.setText(text);
			mHintImage.setClickable(true);
			mHintImage.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					logic.getMyTopic(10, 1, mType, "time");
				}
			});
			mAfterLodingHint.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == 18 && resultCode == getActivity().RESULT_OK){
			isRefreshAction = true;
			logic.getMyTopic(10, 1, mType, "time");
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
时间: 2024-10-13 17:22:17

安卓PullToRefresh自动下拉加载刷新实现的相关文章

安卓,采用最简单易懂的方式实现上拉刷新下拉加载更多

<!-- Description:上拉刷新,下拉加载更多是现在最流行的手势操作,但是对于初学者来说,在实现上是有一定难度的, 网上很多教程讲的都过于复杂,对于初学者无法起到引导作用,特此写本文,帮助安卓新手入门理解此, 还有最为重要的一点:本文只帮助你理解,并不是想你成为代码搬运工!别被那么多代码吓到了, 其中很多都是注释,仔细看注释对你理解有很大的帮助 Author:Booker L Date:2014-05-16 --> 一,事先准备: 实现该功能,最基本的需要两个东西,一个是OnTouc

上拉刷新下拉加载控件-PullToRefresh

在很多软件中,我们会用到上拉刷新,同时大多也会有下拉加载的功能,PullToRefresh这个控件就可以帮我们实现这个效果. 要使用这个空间首先我们要导包 布局文件 布局文件中就是添加了一个最简单的PullToRefreshListView <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/r

jQuery手机端上拉刷新下拉加载更多页面

<!doctype html> <html> <head> <title>jquery 手机端上拉刷新下拉加载更多页面</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta name="viewpost" content="width=device-wi

MUI实现上拉刷新和下拉加载

  前  言 ha ha 为实现下拉刷新功能,大多H5框架都是通过DIV模拟下拉回弹动画,在低端android手机上,DIV动画经常出现卡顿现象(特别是图文列表的情况): mui通过双webview解决这个DIV的拖动流畅度问题:拖动时,拖动的不是div,而是一个完整的webview(子webview),回弹动画使用原生动画. mui的上拉加载和下拉刷新类似,都属于pullRefresh插件. 上拉刷新 主页面内容比较简单,只需要创建子页面即可: mui.init({ subpages:[{ u

Android MVP设计框架模板 之 漂亮ListView上拉刷新下拉加载更多

mvp的全称为Model-View-Presenter,Model提供数据,View负责显示,Controller/Presenter负责逻辑的处理.MVP与MVC有着一个重大的区别:在MVP中View并不直接使用Model,它们之间的通信是通过Presenter (MVC中的Controller)来进行的,所有的交互都发生在Presenter内部,而在MVC中View会直接从Model中读取数据而不是通过 Controller. 项目中大部分是面对接口编程,通过P层可以预先将所有需要的接口功能

如何制作带有下拉刷新和下拉加载更多的列表

一般的APP软件都是需要下拉刷新,下拉加载这两个功能的,今天我们就来学习怎么样实现这两个功能. 我们先来讲一下他们的原理,这里我们将采取的方案是使用组合View的方式,先自定义一个布局继承自LinearLayout,然后在这个布局中加入下拉头和ListView这两个子元素,并让这两个子元素纵向排列.初始化的时候,让下拉头向上偏移出屏幕,这样我们看到的就只有ListView了.然后对ListView的touch事件进行监听,如果当前ListView已经滚动到顶部并且手指还在向下拉的话,那就将下拉头

PullToRefreshGridView上拉刷新,下拉加载

PullToRefreshGridView上拉刷新,下拉加载 布局: 1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 an

iscroll.js实现上拉刷新,下拉加载更多,应用技巧项目实战

上拉刷新,下拉加载更多...仿原生的效果----iscroll是一款做滚动效果的插件,具体介绍我就不废话,看官方文档,我只写下我项目开发的一些用到的用法: (如果不好使,调试你的css,想必是个很蛋疼的问题,给点提示 :#wrapper,以及#scroller-content要注意) html如下: <div class="viewport"> <div id="wrapper" class="wrapper"> <

Android之 RecyclerView,CardView 详解和相对应的上拉刷新下拉加载

随着 Google 推出了全新的设计语言 Material Design,还迎来了新的 Android 支持库 v7,其中就包含了 Material Design 设计语言中关于 Card 卡片概念的实现 -- CardView.RecyclerView也是谷歌V7包下新增的控件,用来替代ListView的使用,在RecyclerView标准化了ViewHolder类似于ListView中convertView用来做视图缓存. RecyclerView的优点就是,他可以通过设置LayoutMan