2011-02-04 183 views
1

我遇到了使用自定义textview在给定位置显示给定文本的问题。onDraw无法访问非静态变量

我想创建设置成圆形方式Ñ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); 

} 

有了这个代码,我得到空指针,因为不能的onDraw访问的变量的内容,与

System.out.println("draw x: "+mx+" y: "+my+" text: "+mtext); 

我得到“0.0 0.0空”,相反,如果我定义变量为静态的,我得到分配给他们的(当然)的最后一个值:

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无法访问除静态类之外的类变量?

谢谢

+2

你能粘贴整个`MyTextView`类? – Cristian 2011-02-04 16:07:57

回答

0

请始终发布有关异常问题的追溯;那会让诊断更容易

在您的类中有一个名为mTextPaint的变量,但它没有在您的构造函数中初始化。它的价值应该是什么?除非它是静态初始化的,否则可能是NPE的原因。

编辑:我猜你的构造需要包括行:

mTextPaint = getPaint(); 
+0

解决!这个paint初始化在initBrushes()中,下面的代码工作: \t \t player_name = new MyTextView(mCtx,x,y,String.valueOf(i + 1)); \t \t ll.addView(player_name); 从布局xml文件中删除 \t。 – Biagio 2011-02-04 16:52:57