1. 程式人生 > >(Android)五分鐘讓你輕鬆學會下拉重新整理和上拉載入更多

(Android)五分鐘讓你輕鬆學會下拉重新整理和上拉載入更多

分享一個谷歌自帶的下拉重新整理和上拉載入更多例子:

先看效果圖:


/**
 * 繼承自SwipeRefreshLayout,從而實現滑動到底部時上拉載入更多的功能.
 */
public class RefreshLayout extends SwipeRefreshLayout implements
		OnScrollListener {

	/**
	 * 滑動到最下面時的上拉操作
	 */

	private int mTouchSlop;
	/**
	 * listview例項
	 */
	private ListView mListView;

	/**
	 * 上拉監聽器, 到了最底部的上拉載入操作
	 */
	private OnLoadListener mOnLoadListener;

	/**
	 * ListView的載入中footer
	 */
	private View mListViewFooter;

	/**
	 * 按下時的y座標
	 */
	private int mYDown;
	/**
	 * 擡起時的y座標, 與mYDown一起用於滑動到底部時判斷是上拉還是下拉
	 */
	private int mLastY;
	/**
	 * 是否在載入中 ( 上拉載入更多 )
	 */
	private boolean isLoading = false;

	/**
	 * @param context
	 */
	public RefreshLayout(Context context) {
		this(context, null);
	}

	@SuppressLint("InflateParams")
	public RefreshLayout(Context context, AttributeSet attrs) {
		super(context, attrs);

		mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

		mListViewFooter = LayoutInflater.from(context).inflate(
				R.layout.listview_footer, null, false);
	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		super.onLayout(changed, left, top, right, bottom);
		// 初始化ListView物件
		if (mListView == null) {
			getListView();
		}
	}

	/**
	 * 獲取ListView物件
	 */
	private void getListView() {
		int childs = getChildCount();
		if (childs > 0) {
			View childView = getChildAt(0);
			if (childView instanceof ListView) {
				mListView = (ListView) childView;
				// 設定滾動監聽器給ListView, 使得滾動的情況下也可以自動載入
				mListView.setOnScrollListener(this);
				Log.d(VIEW_LOG_TAG, "### 找到listview");
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		final int action = event.getAction();

		switch (action) {
		case MotionEvent.ACTION_DOWN:
			// 按下
			mYDown = (int) event.getRawY();
			break;

		case MotionEvent.ACTION_MOVE:
			// 移動
			mLastY = (int) event.getRawY();
			break;

		case MotionEvent.ACTION_UP:
			// 擡起
			if (canLoad()) {
				loadData();
			}
			break;
		default:
			break;
		}

		return super.dispatchTouchEvent(event);
	}

	/**
	 * 是否可以載入更多, 條件是到了最底部, listview不在載入中, 且為上拉操作.
	 * 
	 * @return
	 */
	private boolean canLoad() {
		return isBottom() && !isLoading && isPullUp();
	}

	/**
	 * 判斷是否到了最底部
	 */
	private boolean isBottom() {

		if (mListView != null && mListView.getAdapter() != null) {
			return mListView.getLastVisiblePosition() == (mListView
					.getAdapter().getCount() - 1);
		}
		return false;
	}

	/**
	 * 是否是上拉操作
	 * 
	 * @return
	 */
	private boolean isPullUp() {
		return (mYDown - mLastY) >= mTouchSlop;
	}

	/**
	 * 如果到了最底部,而且是上拉操作.那麼執行onLoad方法
	 */
	private void loadData() {
		if (mOnLoadListener != null) {
			// 設定狀態
			setLoading(true);
			//
			mOnLoadListener.onLoad();
		}
	}

	/**
	 * @param loading
	 */
	public void setLoading(boolean loading) {
		isLoading = loading;
		if (isLoading) {
			mListView.addFooterView(mListViewFooter);
		} else {
			mListView.removeFooterView(mListViewFooter);
			mYDown = 0;
			mLastY = 0;
		}
	}

	/**
	 * @param loadListener
	 */
	public void setOnLoadListener(OnLoadListener loadListener) {
		mOnLoadListener = loadListener;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// 滾動時到了最底部也可以載入更多
		if (canLoad()) {
			loadData();
		}
	}
	
	/**
	 * 設定重新整理
	 */
	public static void setRefreshing(SwipeRefreshLayout refreshLayout,
			boolean refreshing, boolean notify) {
		Class<? extends SwipeRefreshLayout> refreshLayoutClass = refreshLayout
				.getClass();
		if (refreshLayoutClass != null) {

			try {
				Method setRefreshing = refreshLayoutClass.getDeclaredMethod(
						"setRefreshing", boolean.class, boolean.class);
				setRefreshing.setAccessible(true);
				setRefreshing.invoke(refreshLayout, refreshing, notify);
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 載入更多的監聽器
	 */
	public static interface OnLoadListener {
		public void onLoad();
	}
}

自定義介面卡
public class MyAdapter extends BaseAdapter {
	public ArrayList<HashMap<String, String>> list;
	public Context context;
	public LayoutInflater layoutInflater;

	public MyAdapter(Context context, ArrayList<HashMap<String, String>> list) {
		this.context = context;
		this.list = list;
		layoutInflater = LayoutInflater.from(context);
	}

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

	@Override
	public Object getItem(int position) {
		return null;
	}

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = null;
		ViewHolder holder = null;
		if (convertView == null) {
			view = layoutInflater.inflate(R.layout.item, null);
			holder = new ViewHolder();
			holder.txt  =(TextView) view.findViewById(R.id.textView1);
			view.setTag(holder);
		} else {
			view = convertView;
			holder = (ViewHolder) view.getTag();
		}
		holder.txt.setText(list.get(position).get("itemText"));
		return view;
	}

	static class ViewHolder {
		
		TextView txt;
	}

}

新建一個Activity展示
public class MainActivity extends Activity implements OnRefreshListener,
		OnLoadListener {
	private RefreshLayout swipeLayout;
	private ListView listView;
	private MyAdapter adapter;
	private ArrayList<HashMap<String, String>> list;
	private View header;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		setData();
		setListener();
		/*設定自動重新整理 swipeLayout.setRefreshing(true);
		在 setRefreshing(true)並沒有觸發onRefresh的,須要手動呼叫一次
        */
//		swipeLayout.post(new Thread(new Runnable() {
//			@Override
//			public void run() {
//				swipeLayout.setRefreshing(true);
//			}
//		}));
//		onRefresh();
	}

	/**
	 * 初始化佈局
	 */
	@SuppressLint({ "InlinedApi", "InflateParams" })
	private void initView() {
		header = getLayoutInflater().inflate(R.layout.header, null);
		swipeLayout = (RefreshLayout) findViewById(R.id.swipe_container);
		swipeLayout.setColorSchemeResources(R.color.color_bule2,R.color.color_bule,R.color.color_bule2,R.color.color_bule3);
	}

	/**
	 * 新增資料
	 */
	private void setData() {
		list = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < 10; i++) {
		    HashMap<String, String> map = new HashMap<String, String>();  
            map.put("itemImage", i+"預設");  
            map.put("itemText", i+"預設");  
            list.add(map);
		}
		listView = (ListView) findViewById(R.id.list);
		listView.addHeaderView(header);
		adapter = new MyAdapter(this, list);
		listView.setAdapter(adapter);
	}

	/**
	 * 設定監聽
	 */
	private void setListener() {
		swipeLayout.setOnRefreshListener(this);
		swipeLayout.setOnLoadListener(this);
	}

	/**
	 * 上拉重新整理
	 */
	@Override
	public void onRefresh() {
		swipeLayout.postDelayed(new Runnable() {

			@Override
			public void run() {
				// 更新資料  更新完後呼叫該方法結束重新整理
				list.clear();
				for (int i = 0; i < 8; i++) {
				    HashMap<String, String> map = new HashMap<String, String>();  
		            map.put("itemImage", i+"重新整理");  
		            map.put("itemText", i+"重新整理");  
		            list.add(map);
				}
				adapter.notifyDataSetChanged();
				swipeLayout.setRefreshing(false);
			}
		}, 2000);

	}

	/**
	 * 載入更多
	 */
	@Override
	public void onLoad() {
		swipeLayout.postDelayed(new Runnable() {
			@Override
			public void run() {
				// 更新資料  更新完後呼叫該方法結束重新整理
				swipeLayout.setLoading(false);
				for (int i = 1; i < 10; i++) {
				    HashMap<String, String> map = new HashMap<String, String>();  
		            map.put("itemImage", i+"更多");  
		            map.put("itemText", i+"更多");  
		            list.add(map);
				}
				adapter.notifyDataSetChanged();
			}
		}, 2000);
	}

原始碼下載

感興趣掃描一下二維碼關注一下,或加微訊號:aikaifa

回覆 重新整理 關鍵字即可


愛開發致力於成為中國創業者的資訊平臺和服務平臺,幫助開發者實現創業夢想。愛開發為開發者提供各種創業類最新資訊和實用知識手冊,打造為開發者提供高價值的資訊平臺。