1. 程式人生 > >Android PickerView的實現

Android PickerView的實現

話不多說,直接上圖
這裡寫圖片描述

這樣子的PickerView,也就是自定義一個View。直接上程式碼

/*
 * 使用:xml檔案中直接引用,需要多少列資料就用多少個PickerView
 * 在Activity中:獲取到PickerView例項後,使用setData()方法設定資料,其他方法見103行
 * 關聯資料:比如現在第一列選中xx市,可以在監聽中為第二個PickerView呼叫setData()來更新第二列的資料
 */
public class PickerView 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<String> mDataList; /** * 預設初始化時選中的位置,這個位置是mDataList的中心位置,一直不變 */ private int mCurrentSelected; private
Paint mPaint; private float mMaxTextSize = 80; private float mMinTextSize = 40; 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(); } }; //構造方法都呼叫init public PickerView(Context context) { super(context); init(); } public PickerView(Context context, AttributeSet attrs) { super(context, attrs); init(); } //以下為主要使用的public方法--------------------------------------------------------------------------------- /* * 獲取到當前選中的資料在資料集中的position */ public int getCurrentItem(){ return mCurrentSelected; }; /* * 設定監聽,這個onSelectedLisener需要實現一個onSelect(String text)方法 * text是當前顯示的資料 */ public void setOnSelectListener(onSelectListener listener) { mSelectListener = listener; } /* * 設定資料集,引數型別為List */ public void setData(List<String> datas) { mDataList = datas; mCurrentSelected = datas.size() / 2; invalidate(); } /* * 設定當前選中的資料 */ public void setSelected(int selected) { mCurrentSelected = selected; } //------------------------------------------------------------------------------------- private void performSelect() { if (mSelectListener != null) mSelectListener.onSelect(mDataList.get(mCurrentSelected)); } private void moveHeadToTail() { String head = mDataList.get(0); mDataList.remove(0); mDataList.add(head); } private void moveTailToHead() { String 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 / 4.0f; mMinTextSize = mMaxTextSize / 2f; isInit = true; invalidate(); } private void init() { timer = new Timer(); mDataList = new ArrayList<String>(); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setStyle(Paint.Style.FILL); mPaint.setTextAlign(Paint.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); Paint.FontMetricsInt fmi = mPaint.getFontMetricsInt(); float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0)); canvas.drawText(mDataList.get(mCurrentSelected), x, baseline, mPaint); Paint linePaint=new Paint(); linePaint.setColor(Color.LTGRAY); linePaint.setStrokeWidth(3); // 繪製上方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); Paint.FontMetricsInt fmi = mPaint.getFontMetricsInt(); float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0)); canvas.drawText(mDataList.get(mCurrentSelected + type * position), (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(String text); }

在xml中引用

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <LinearLayout
        android:layout_centerHorizontal="true"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <com.liu.pickerview.PickerView
            android:id="@+id/year_picker"
            android:layout_width="100dp"
            android:layout_height="100dp" />
        <com.liu.pickerview.PickerView
            android:id="@+id/month_picker"
            android:layout_width="100dp"
            android:layout_height="100dp" />
    </LinearLayout>

</RelativeLayout>

在java程式碼中呼叫

public class MainActivity extends AppCompatActivity {
    private PickerView year, month;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        year = (PickerView) findViewById(R.id.year_picker);
        month = (PickerView) findViewById(R.id.month_picker);

        ArrayList<String> month_list=new ArrayList<>();
        for (int i=0;i<12;i++){
            month_list.add(i + "");
        }
        ArrayList<String> year_list=new ArrayList<>();
        for (int i=0;i<100;i++){
            year_list.add( i + "");
        }

        year.setData(year_list);
        month.setData(month_list);


        year.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                Log.i("tag","選擇了"+text);
            }
        });
        month.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                Log.i("tag","選擇了"+text);
            }
        });
    }
}