我遇到使用自定义文本视图在给定位置显示给定文本的问题。
我想使用以下代码创建以循环方式放置的N MyTextView:
for (int i = 0; i < player_num ; i++){
x = (x_offset+(raggio*Math.sin((degree_offset)*i)));
y = (y_offset+(raggio*Math.cos((degree_offset)*i)));
//System.out.println("x: "+x+" y: "+y);
player_name = new MyTextView(mCtx,x,y,String.valueOf(i+1));
}
这是我的一个扩展TextView的类,我传递x,y坐标和显示的字符串:
public MyTextView(Context context, double x, double y, String text) {
super(context);
System.out.println("constructor called");
mx = x;
my = y;
mtext = text;
initBrushes();
System.out.println("constructor x: "+mx+" y: "+my+" text: "+mtext);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Get the size of the control based on the last call to onMeasure.
int height = getMeasuredHeight();
int width = getMeasuredWidth();
System.out.println("ondraw called");
System.out.println("draw x: "+mx+" y: "+my+" text: "+mtext);
// Find the center
int px = width / 2;
int py = height / 2;
// Define the string.
// Measure the width of the text string.
float textWidth = mTextPaint.measureText(mtext);
// Draw the text string in the center of the control.
canvas.drawText(mtext, Math.round(mx) - textWidth / 2, Math.round(my)- textWidth, mTextPaint);
//canvas.drawText(this.text, Math.round(this.x), Math.round(this.y), mTextPaint);
}
使用此代码我得到NullPointer因为onDraw无法访问变量的内容,而
System.out.println("draw x: "+mx+" y: "+my+" text: "+mtext);
我得到“0.0 0.0 null”,相反,如果我将变量定义为静态,我会得到分配给它们的最后一个值(当然):
constructor called
constructor x: 160.0 y: 320.0 text: 1
constructor called
constructor x: 206.44889473698515 y: 305.1344776421249 text: 2
constructor called
constructor x: 235.63561239368934 y: 266.0625044428118 text: 3
ondraw called
draw x: 235.63561239368934 y: 266.0625044428118 text: 3
我做错了什么?为什么onDraw无法访问除静态变量之外的类变量?
谢谢
答案 0 :(得分:0)
请始终发布追溯以了解有关例外的问题;这将使诊断更多更容易。
您的类中有一个名为mTextPaint
的变量,但它未在构造函数中初始化。应该是什么价值?除非它是静态初始化的,否则它可能是你的NPE的原因。
编辑:我猜你的构造函数需要包含这一行:
mTextPaint = getPaint();