来先看效果图:
看效果图是不是很简单?
简单讲一下思路 具体的代码大家可以去下载源代码来自己看。
1.自定义继承View
2.重写onMeasure()方法 计算控件的宽高
//高度
int height = MeasureSpec.getSize(heightMeasureSpec);
//宽度 padding 加上文字的一半
int textWidth = (int)mUnselectedPaint.measureText("A");
int width = getPaddingLeft() + getPaddingRight() + textWidth;
setMeasuredDimension(width,height);
3.重写onDraw()方法
//每一个字母控件的高度
int letterHeight = (getHeight() - getPaddingTop() - getPaddingBottom()) /mLetters.length;
for(int i=0;i
int textWidth = (int)mUnselectedPaint.measureText(mLetters[i]);
int dx = getWidth()/2 - textWidth/2;
int dy = i * letterHeight + letterHeight/2 + getPaddingTop();
Paint.FontMetricsInt fontMetricsInt =mUnselectedPaint.getFontMetricsInt();
int y = (fontMetricsInt.bottom - fontMetricsInt.top)/2 - fontMetricsInt.bottom;
int baseLine = y + dy;
if(mLetters[i].equals(mCurrentSelectedLetter)){
canvas.drawText(mLetters[i], dx, baseLine, mSelectedPaint);
}else {
canvas.drawText(mLetters[i], dx, baseLine, mUnselectedPaint);
}
}
4.最后的onTouchEvent()
*****记住一定是 return true 否则无法滑动
switch (event.getAction()){
case MotionEvent.ACTION_DOWN :
case MotionEvent.ACTION_MOVE:
float y = event.getY();
int letterHeight = (getHeight() - getPaddingTop() - getPaddingBottom()) /mLetters.length;
int centerY = (int)(y/letterHeight);
if(centerY >=0 && centerY
String mLetter =mLetters[centerY];
if(!mLetter.equals(mCurrentSelectedLetter)){
mCurrentSelectedLetter = mLetter;
if(this.letterListener!=null) {
this.letterListener.selected(mCurrentSelectedLetter);
}
invalidate();
}
}
break;
case MotionEvent.ACTION_UP:
if(this.letterListener!=null) {
mCurrentSelectedLetter =null;
this.letterListener.selected(null);
invalidate();
}
break;
}
return true;
好了,到这里就完毕了 代码如下:
网友评论