这个工程还是自定义View的通用写法,倒也没什么多说的,这次的学习总结是记录自定义RatingBar中的接口回调,绘制竖列字母的过程。
接口回调方法:
屏幕当中的TextView需要两个值:当前选中字母的值以及是否隐藏。故接口方法接收两个参数:
public interface MyRationgBarListener{
void touch(String m,boolean isShow);
}
感觉接口回调就是用来在两个类之间实时传递数据。
绘制字母竖列:
工程中重写了onMeasure()方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int textwidth = (int) normalPaint.measureText("A");
int width = (int)(getPaddingLeft()+getPaddingRight()+textwidth);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width,height);
}
xml文件中的属性设置:
<com.example.chang.myratingbar.RatingBar
android:id="@+id/ratingBar_main"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:paddingRight="10sp"
/>
onDraw()方法:
@Override
protected void onDraw(Canvas canvas) {
for(int i = 0;i < items.length;i++){
int textWidth = (int) normalPaint.measureText(items[i]);
int x = getWidth()/2 - textWidth/2;
Paint.FontMetrics fontMetrics = normalPaint.getFontMetrics();
int dy = (int) ((fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom);
int itemHeight = (getHeight() - getPaddingTop() - getPaddingBottom()) / (items.length);
int baseline = i * itemHeight + (itemHeight / 2)+dy;
Log.d(TAG, "onDraw: "+currentPosition);
if(i != currentPosition){
canvas.drawText(items[i],x,baseline,normalPaint);
}else {
canvas.drawText(items[i],x,baseline,focusPaint);
}
}
}