2011-02-04 115 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