1. 程式人生 > >Android 仿 iphone 自定義滾動選擇器

Android 仿 iphone 自定義滾動選擇器

背景:其實我們都知道,在我們做開發的過程中,會遇到Android 自身所帶控制元件不夠的情況,那麼這個時候,就需要我們自定義控制元件,所以,也就造成了,在開發的過程中,我們一定要掌握好自定義控制元件,不然,當你去一家公司,產品萌妹子過來找你,這個效果很不錯,問你能不能實現的時候,你難道能有理由說不行麼,男人嘛,哪裡能說不行了,直接用渾厚的聲音告訴她,行,怎麼不行,直接KO她。

一:多的不說,效果圖,先走起


二:例項原始碼

(1)自定義控制元件

package com.pickerscrollview.views;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Paint.Style;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.pickerscrollview.bean.Pickers;

/**
 * 自定義滾動選擇器
 * 
 * @author zengtao 2015年5月20日 下午7:36:03
 *
 */
@SuppressLint({ "HandlerLeak", "ClickableViewAccessibility" })
public class PickerScrollView extends View {

	public static final String TAG = "PickerView";
	/**
	 * text之間間距和minTextSize之比
	 */
	public static final float MARGIN_ALPHA = 2.8f;
	/**
	 * 自動回滾到中間的速度
	 */
	public static final float SPEED = 2;

	private List<Pickers> mDataList;
	/**
	 * 選中的位置,這個位置是mDataList的中心位置,一直不變
	 */
	private int mCurrentSelected;
	private Paint mPaint;

	private float mMaxTextSize = 20;
	private float mMinTextSize = 10;

	private float mMaxTextAlpha = 255;
	private float mMinTextAlpha = 120;

	private int mColorText = 0x333333;

	private int mViewHeight;
	private int mViewWidth;

	private float mLastDownY;
	/**
	 * 滑動的距離
	 */
	private float mMoveLen = 0;
	private boolean isInit = false;
	private onSelectListener mSelectListener;
	private Timer timer;
	private MyTimerTask mTask;

	Handler updateHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (Math.abs(mMoveLen) < SPEED) {
				mMoveLen = 0;
				if (mTask != null) {
					mTask.cancel();
					mTask = null;
					performSelect();
				}
			} else
				// 這裡mMoveLen / Math.abs(mMoveLen)是為了保有mMoveLen的正負號,以實現上滾或下滾
				mMoveLen = mMoveLen - mMoveLen / Math.abs(mMoveLen) * SPEED;
			invalidate();
		}

	};

	public PickerScrollView(Context context) {
		super(context);
		init();
	}

	public PickerScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public void setOnSelectListener(onSelectListener listener) {
		mSelectListener = listener;
	}

	private void performSelect() {
		if (mSelectListener != null)
			mSelectListener.onSelect(mDataList.get(mCurrentSelected));
	}

	public void setData(List<Pickers> datas) {
		mDataList = datas;
		mCurrentSelected = datas.size() / 2;
		invalidate();
	}

	/**
	 * 選擇選中的item的index
	 * 
	 * @param selected
	 */
	public void setSelected(int selected) {
		mCurrentSelected = selected;
		int distance = mDataList.size() / 2 - mCurrentSelected;
		if (distance < 0)
			for (int i = 0; i < -distance; i++) {
				moveHeadToTail();
				mCurrentSelected--;
			}
		else if (distance > 0)
			for (int i = 0; i < distance; i++) {
				moveTailToHead();
				mCurrentSelected++;
			}
		invalidate();
	}

	/**
	 * 選擇選中的內容
	 * 
	 * @param mSelectItem
	 */
	public void setSelected(String mSelectItem) {
		for (int i = 0; i < mDataList.size(); i++)
			if (mDataList.get(i).equals(mSelectItem)) {
				setSelected(i);
				break;
			}
	}

	private void moveHeadToTail() {
		Pickers head = mDataList.get(0);
		mDataList.remove(0);
		mDataList.add(head);
	}

	private void moveTailToHead() {
		Pickers tail = mDataList.get(mDataList.size() - 1);
		mDataList.remove(mDataList.size() - 1);
		mDataList.add(0, tail);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		mViewHeight = getMeasuredHeight();
		mViewWidth = getMeasuredWidth();
		// 按照View的高度計算字型大小
		mMaxTextSize = mViewHeight / 8.0f;
		mMinTextSize = mMaxTextSize / 2f;
		isInit = true;
		invalidate();
	}

	private void init() {
		timer = new Timer();
		mDataList = new ArrayList<Pickers>();
		mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mPaint.setStyle(Style.FILL);
		mPaint.setTextAlign(Align.CENTER);
		mPaint.setColor(mColorText);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		// 根據index繪製view
		if (isInit)
			drawData(canvas);
	}

	private void drawData(Canvas canvas) {
		// 先繪製選中的text再往上往下繪製其餘的text
		float scale = parabola(mViewHeight / 4.0f, mMoveLen);
		float size = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;
		mPaint.setTextSize(size);
		mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));
		// text居中繪製,注意baseline的計算才能達到居中,y值是text中心座標
		float x = (float) (mViewWidth / 2.0);
		float y = (float) (mViewHeight / 2.0 + mMoveLen);
		FontMetricsInt fmi = mPaint.getFontMetricsInt();
		float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));

		int indexs = mCurrentSelected;
		String textData = mDataList.get(indexs).getShowConetnt();
		canvas.drawText(textData, x, baseline, mPaint);

		// 繪製上方data
		for (int i = 1; (mCurrentSelected - i) >= 0; i++) {
			drawOtherText(canvas, i, -1);
		}
		// 繪製下方data
		for (int i = 1; (mCurrentSelected + i) < mDataList.size(); i++) {
			drawOtherText(canvas, i, 1);
		}
	}

	/**
	 * @param canvas
	 * @param position
	 *            距離mCurrentSelected的差值
	 * @param type
	 *            1表示向下繪製,-1表示向上繪製
	 */
	private void drawOtherText(Canvas canvas, int position, int type) {
		float d = (float) (MARGIN_ALPHA * mMinTextSize * position + type
				* mMoveLen);
		float scale = parabola(mViewHeight / 4.0f, d);
		float size = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;
		mPaint.setTextSize(size);
		mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));
		float y = (float) (mViewHeight / 2.0 + type * d);
		FontMetricsInt fmi = mPaint.getFontMetricsInt();
		float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));

		int indexs = mCurrentSelected + type * position;
		String textData = mDataList.get(indexs).getShowConetnt();
		canvas.drawText(textData, (float) (mViewWidth / 2.0), baseline, mPaint);
	}

	/**
	 * 拋物線
	 * 
	 * @param zero
	 *            零點座標
	 * @param x
	 *            偏移量
	 * @return scale
	 */
	private float parabola(float zero, float x) {
		float f = (float) (1 - Math.pow(x / zero, 2));
		return f < 0 ? 0 : f;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getActionMasked()) {
		case MotionEvent.ACTION_DOWN:
			doDown(event);
			break;
		case MotionEvent.ACTION_MOVE:
			doMove(event);
			break;
		case MotionEvent.ACTION_UP:
			doUp(event);
			break;
		}
		return true;
	}

	private void doDown(MotionEvent event) {
		if (mTask != null) {
			mTask.cancel();
			mTask = null;
		}
		mLastDownY = event.getY();
	}

	private void doMove(MotionEvent event) {

		mMoveLen += (event.getY() - mLastDownY);

		if (mMoveLen > MARGIN_ALPHA * mMinTextSize / 2) {
			// 往下滑超過離開距離
			moveTailToHead();
			mMoveLen = mMoveLen - MARGIN_ALPHA * mMinTextSize;
		} else if (mMoveLen < -MARGIN_ALPHA * mMinTextSize / 2) {
			// 往上滑超過離開距離
			moveHeadToTail();
			mMoveLen = mMoveLen + MARGIN_ALPHA * mMinTextSize;
		}

		mLastDownY = event.getY();
		invalidate();
	}

	private void doUp(MotionEvent event) {
		// 擡起手後mCurrentSelected的位置由當前位置move到中間選中位置
		if (Math.abs(mMoveLen) < 0.0001) {
			mMoveLen = 0;
			return;
		}
		if (mTask != null) {
			mTask.cancel();
			mTask = null;
		}
		mTask = new MyTimerTask(updateHandler);
		timer.schedule(mTask, 0, 10);
	}

	class MyTimerTask extends TimerTask {
		Handler handler;

		public MyTimerTask(Handler handler) {
			this.handler = handler;
		}

		@Override
		public void run() {
			handler.sendMessage(handler.obtainMessage());
		}

	}

	public interface onSelectListener {
		void onSelect(Pickers pickers);
	}
}
(2)實體類
package com.pickerscrollview.bean;

import java.io.Serializable;

/**
 * 
 * @author zengtao 2015年5月20日下午7:18:14
 *
 */
public class Pickers implements Serializable {

	private static final long serialVersionUID = 1L;

	private String showConetnt;
	private String showId;

	public String getShowConetnt() {
		return showConetnt;
	}

	public String getShowId() {
		return showId;
	}

	public Pickers(String showConetnt, String showId) {
		super();
		this.showConetnt = showConetnt;
		this.showId = showId;
	}

	public Pickers() {
		super();
	}

}


(3)主介面
package com.pickerscrollview.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.pickerscrollview.bean.Pickers;
import com.pickerscrollview.views.PickerScrollView;
import com.pickerscrollview.views.PickerScrollView.onSelectListener;

/**
 * 主介面
 * 
 * @author zengtao 2015年5月20日 下午7:36:03
 *
 */
public class MainActivity extends Activity {

	private Button bt_scrollchoose; // 滾動選擇器按鈕
	private PickerScrollView pickerscrlllview; // 滾動選擇器
	private List<Pickers> list; // 滾動選擇器資料
	private String[] id;
	private String[] name;

	private Button bt_yes; // 確定按鈕
	private RelativeLayout picker_rel; // 選擇器佈局

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

		initView();
		initLinstener();
		initData();
	}

	/**
	 * 初始化
	 */
	private void initView() {
		bt_scrollchoose = (Button) findViewById(R.id.bt_scrollchoose);
		picker_rel = (RelativeLayout) findViewById(R.id.picker_rel);
		pickerscrlllview = (PickerScrollView) findViewById(R.id.pickerscrlllview);
		bt_yes = (Button) findViewById(R.id.picker_yes);
	}

	/**
	 * 設定監聽事件
	 */
	private void initLinstener() {
		bt_scrollchoose.setOnClickListener(onClickListener);
		pickerscrlllview.setOnSelectListener(pickerListener);
		bt_yes.setOnClickListener(onClickListener);
	}

	/**
	 * 初始化資料
	 */
	private void initData() {
		list = new ArrayList<Pickers>();
		id = new String[] { "1", "2", "3", "4", "5", "6" };
		name = new String[] { "中國銀行", "農業銀行", "招商銀行", "工商銀行", "建設銀行", "民生銀行" };
		for (int i = 0; i < name.length; i++) {
			list.add(new Pickers(name[i], id[i]));
		}
		// 設定資料,預設選擇第一條
		pickerscrlllview.setData(list);
		pickerscrlllview.setSelected(0);
	}

	// 滾動選擇器選中事件
	onSelectListener pickerListener = new onSelectListener() {

		@Override
		public void onSelect(Pickers pickers) {
			System.out.println("選擇:" + pickers.getShowId() + "--銀行:"
					+ pickers.getShowConetnt());
		}
	};

	// 點選監聽事件
	OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (v == bt_scrollchoose) {
				picker_rel.setVisibility(View.VISIBLE);
			} else if (v == bt_yes) {
				picker_rel.setVisibility(View.GONE);
			}
		}
	};
}

三:總結

先做一下解析,在滑動手指的時候,有一個突出的點,就是有點像圓弧那個弧度一樣的感覺,所以我們要用parabola這個方法去計算出來,畫多大的字也是需要計算控制元件的高度,和寬度來繪製,首先我們先繪製中間的文體,在繪製上下兩邊的字,當然,我們也要設定一個手勢監聽,用於監聽使用者按下,滑動,擡起的時候,的一個操作,我們會根據手指往上移動和向下移動距離的多少來判斷顯示那個文字,選中了那個。