手机里设置闹钟需要选择时间,那个选择时间的控件就是滚动选择器,前几天用手机刷了MIUI,发现自带的那个时间选择器效果挺好看的,于是就自己仿写了一个,权当练手。先来看效果:


效果还行吧?实现思路就是自定义一个PickerView,单独滚动的是一个PickerView,显然上图中有分和秒的选择所以在布局里用了两个PickerView。由于这里不涉及到text的点击事件,所以只需要继承View就行了,直接把text用canvas画上去。PickerView的实现的主要难点:

难点1:

字体随距离的渐变。可以看到,text随离中心位置的距离变化而变化,这里变化的是透明度alpha和字体大小TexSize,这两个值我都设置了Max和Min值,通过其与中心点的距离计算scale。我用的是变化曲线是抛物线scale=1-ax^2(x<=Height/4),scale = 0(x>Height/4),a=(4/Height)^2。x就是距离View中心的偏移量。用图片表示如下:


难点2:

text的居中。绘制text的时候不仅要使其在x方向上居中,还要在y方向上居中,在x方向上比较简单,设置Paint的Align为Align.CENTER就行了,但是y方向上很蛋疼,需要计算text的baseline。

难点3:

循环滚动。为了解决循环滚动的问题我把存放text的List从中间往上下摊开,通过不断地moveHeadToTail和moveTailToHead使选中的text始终是list的中间position的值。

以上就是几个难点,了解了之后可以来看PickerView的代码了:

packagecom.jingchen.timerpicker;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Timer;
importjava.util.TimerTask;
importandroid.content.Context;
importandroid.graphics.Canvas;
importandroid.graphics.Paint;
importandroid.graphics.Paint.Align;
importandroid.graphics.Paint.FontMetricsInt;
importandroid.graphics.Paint.Style;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.util.AttributeSet;
importandroid.view.MotionEvent;
importandroid.view.View;
/**
* 滚动选择器
*
* @author chenjing
*
*/
publicclassPickerViewextendsView
{
publicstaticfinalString TAG ="PickerView";
/**
* text之间间距和minTextSize之比
*/
publicstaticfinalfloatMARGIN_ALPHA =2.8f;
/**
* 自动回滚到中间的速度
*/
publicstaticfinalfloatSPEED =2;
privateList mDataList;
/**
* 选中的位置,这个位置是mDataList的中心位置,一直不变
*/
privateintmCurrentSelected;
privatePaint mPaint;
privatefloatmMaxTextSize =80;
privatefloatmMinTextSize =40;
privatefloatmMaxTextAlpha =255;
privatefloatmMinTextAlpha =120;
privateintmColorText =0x333333;
privateintmViewHeight;
privateintmViewWidth;
privatefloatmLastDownY;
/**
* 滑动的距离
*/
privatefloatmMoveLen =0;
privatebooleanisInit =false;
privateonSelectListener mSelectListener;
privateTimer timer;
privateMyTimerTask mTask;
Handler updateHandler = newHandler()
{
@Override
publicvoidhandleMessage(Message msg)
{
if(Math.abs(mMoveLen) 
{
mMoveLen = 0;
if(mTask !=null)
{
mTask.cancel();
mTask = null;
performSelect();
}
} else
// 这里mMoveLen / Math.abs(mMoveLen)是为了保有mMoveLen的正负号,以实现上滚或下滚
mMoveLen = mMoveLen - mMoveLen / Math.abs(mMoveLen) * SPEED;
invalidate();
}
};
publicPickerView(Context context)
{
super(context);
init();
}
publicPickerView(Context context, AttributeSet attrs)
{
super(context, attrs);
init();
}
publicvoidsetOnSelectListener(onSelectListener listener)
{
mSelectListener = listener;
}
privatevoidperformSelect()
{
if(mSelectListener !=null)
mSelectListener.onSelect(mDataList.get(mCurrentSelected));
}
publicvoidsetData(List datas)
{
mDataList = datas;
mCurrentSelected = datas.size() / 2;
invalidate();
}
publicvoidsetSelected(intselected)
{
mCurrentSelected = selected;
}
privatevoidmoveHeadToTail()
{
String head = mDataList.get(0);
mDataList.remove(0);
mDataList.add(head);
}
privatevoidmoveTailToHead()
{
String tail = mDataList.get(mDataList.size() - 1);
mDataList.remove(mDataList.size() - 1);
mDataList.add(0, tail);
}
@Override
protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mViewHeight = getMeasuredHeight();
mViewWidth = getMeasuredWidth();
// 按照View的高度计算字体大小
mMaxTextSize = mViewHeight / 4.0f;
mMinTextSize = mMaxTextSize / 2f;
isInit = true;
invalidate();
}
privatevoidinit()
{
timer = newTimer();
mDataList = newArrayList();
mPaint = newPaint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Style.FILL);
mPaint.setTextAlign(Align.CENTER);
mPaint.setColor(mColorText);
}
@Override
protectedvoidonDraw(Canvas canvas)
{
super.onDraw(canvas);
// 根据index绘制view
if(isInit)
drawData(canvas);
}
privatevoiddrawData(Canvas canvas)
{
// 先绘制选中的text再往上往下绘制其余的text
floatscale = parabola(mViewHeight /4.0f, mMoveLen);
floatsize = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;
mPaint.setTextSize(size);
mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));
// text居中绘制,注意baseline的计算才能达到居中,y值是text中心坐标
floatx = (float) (mViewWidth /2.0);
floaty = (float) (mViewHeight /2.0+ mMoveLen);
FontMetricsInt fmi = mPaint.getFontMetricsInt();
floatbaseline = (float) (y - (fmi.bottom /2.0+ fmi.top /2.0));
canvas.drawText(mDataList.get(mCurrentSelected), x, baseline, mPaint);
// 绘制上方data
for(inti =1; (mCurrentSelected - i) >=0; i++)
{
drawOtherText(canvas, i, -1);
}
// 绘制下方data
for(inti =1; (mCurrentSelected + i) 
{
drawOtherText(canvas, i, 1);
}
}
/**
* @param canvas
* @param position
*            距离mCurrentSelected的差值
* @param type
*            1表示向下绘制,-1表示向上绘制
*/
privatevoiddrawOtherText(Canvas canvas,intposition,inttype)
{
floatd = (float) (MARGIN_ALPHA * mMinTextSize * position + type
* mMoveLen);
floatscale = parabola(mViewHeight /4.0f, d);
floatsize = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;
mPaint.setTextSize(size);
mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));
floaty = (float) (mViewHeight /2.0+ type * d);
FontMetricsInt fmi = mPaint.getFontMetricsInt();
floatbaseline = (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
*/
privatefloatparabola(floatzero,floatx)
{
floatf = (float) (1- Math.pow(x / zero,2));
returnf <0?0: f;
}
@Override
publicbooleanonTouchEvent(MotionEvent event)
{
switch(event.getActionMasked())
{
caseMotionEvent.ACTION_DOWN:
doDown(event);
break;
caseMotionEvent.ACTION_MOVE:
doMove(event);
break;
caseMotionEvent.ACTION_UP:
doUp(event);
break;
}
returntrue;
}
privatevoiddoDown(MotionEvent event)
{
if(mTask !=null)
{
mTask.cancel();
mTask = null;
}
mLastDownY = event.getY();
}
privatevoiddoMove(MotionEvent event)
{
mMoveLen += (event.getY() - mLastDownY);
if(mMoveLen > MARGIN_ALPHA * mMinTextSize /2)
{
// 往下滑超过离开距离
moveTailToHead();
mMoveLen = mMoveLen - MARGIN_ALPHA * mMinTextSize;
} elseif(mMoveLen 
{
// 往上滑超过离开距离
moveHeadToTail();
mMoveLen = mMoveLen + MARGIN_ALPHA * mMinTextSize;
}
mLastDownY = event.getY();
invalidate();
}
privatevoiddoUp(MotionEvent event)
{
// 抬起手后mCurrentSelected的位置由当前位置move到中间选中位置
if(Math.abs(mMoveLen) <0.0001)
{
mMoveLen = 0;
return;
}
if(mTask !=null)
{
mTask.cancel();
mTask = null;
}
mTask = newMyTimerTask(updateHandler);
timer.schedule(mTask, 0,10);
}
classMyTimerTaskextendsTimerTask
{
Handler handler;
publicMyTimerTask(Handler handler)
{
this.handler = handler;
}
@Override
publicvoidrun()
{
handler.sendMessage(handler.obtainMessage());
}
}
publicinterfaceonSelectListener
{
voidonSelect(String text);
}
}

代码里的注释都写的很清楚了。接下来,我们就用写好的PickerView实现文章开头的图片效果吧~

首先看MainActivity的布局:

android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#ffffff">
android:id="@+id/minute_pv"
android:layout_width="80dp"
android:layout_height="160dp"/>
android:id="@+id/minute_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/minute_pv"
android:text="分"
android:textColor="#ffaa33"
android:textSize="26sp"
android:textStyle="bold"/>
android:id="@+id/second_pv"
android:layout_width="80dp"
android:layout_height="160dp"
android:layout_toRightOf="@id/minute_tv"/>
android:id="@+id/second_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/second_pv"
android:text="秒"
android:textColor="#ffaa33"
android:textSize="26sp"
android:textStyle="bold"/>

两个PickerView两个TextView,很简单。

下面是MainActivity的代码:

packagecom.jingchen.timerpicker;
importjava.util.ArrayList;
importjava.util.List;
importcom.jingchen.timerpicker.PickerView.onSelectListener;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.view.Menu;
importandroid.widget.TextView;
importandroid.widget.Toast;
publicclassMainActivityextendsActivity
{
PickerView minute_pv;
PickerView second_pv;
@Override
protectedvoidonCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
minute_pv = (PickerView) findViewById(R.id.minute_pv);
second_pv = (PickerView) findViewById(R.id.second_pv);
List data = newArrayList();
List seconds = newArrayList();
for(inti =0; i <10; i++)
{
data.add("0"+ i);
}
for(inti =0; i <60; i++)
{
seconds.add(i 
}
minute_pv.setData(data);
minute_pv.setOnSelectListener(newonSelectListener()
{
@Override
publicvoidonSelect(String text)
{
Toast.makeText(MainActivity.this,"选择了 "+ text +" 分",
Toast.LENGTH_SHORT).show();
}
});
second_pv.setData(seconds);
second_pv.setOnSelectListener(newonSelectListener()
{
@Override
publicvoidonSelect(String text)
{
Toast.makeText(MainActivity.this,"选择了 "+ text +" 秒",
Toast.LENGTH_SHORT).show();
}
});
}
@Override
publicbooleanonCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
returntrue;
}
}

OK了,自定义自己的TimerPicker就是这么简单~