我有一个自定义视图,它会相应地在画布中绘制文本:
public class MTextView extends View {
public String fontFamily = "default";
public float fontSize = 14;
public String text = "Hello";
public int fontFillColor;
private Paint textPaint = new Paint();
private Rect bound = new Rect();
public MTextView(Context context) {
this(context, null);
}
public MTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (text == null || text.equals("")) return;
textPaint.setColor(fontFillColor);
textPaint.setTextSize(fontSize);
textPaint.setTypeface(getTypeFace());
canvas.drawText(text, 10, 60, textPaint);
textPaint.getTextBounds(text, 0, text.length() - 1, bound);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(bound.width(), bound.height());
Log.d("view", bound + "");
}
}
现在,一旦我将这个视图添加到布局中,我就看不到这个视图了,我总是得到这样的日志:
view Rect(0, 0 - 0, 0)
似乎onMeasure
没有得到真正的维度。
如何解决?