2011-02-04 14 views
1

カスタムテキストビューを使用して、指定された位置に特定のテキストを表示する際に問題が発生しました。私はN MyTextViewを作成するonDrawは非静的変数にアクセスできません

このコードを使用して、円形の方法で配置:

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を拡張私のクラスの一部であり、Iは、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); 
で、変数のコンテンツにアクセスカントので、私がnullpointerを取得私は静的として変数を定義した場合

私は「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

答えて

0

例外についての質問は常にトレースバックを投稿してください。それは診断を多くを容易にするでしょう。

あなたのクラスにはmTextPaintという名前の変数がありますが、コンストラクタでは初期化されていません。その価値は何であるはずですか?静的に初期化されていない限り、おそらくあなたのNPEの原因です。

EDIT:私はあなたのコンストラクタは行を含める必要があると推測している:

mTextPaint = getPaint(); 
+0

解決済み!ペイントはinitBrushes()で初期化され、次のコードが機能します。 \t \t player_name = new MyTextView(mCtx、x、y、String.valueOf(i + 1)); \t \t ll.addView(player_name); レイアウトxmlファイルから \tを削除した後。 – Biagio

+0

@Biagioあなたは解決策を説明するために、あなたの解決策を新しい答えとして追加する必要があります。あなたはそれが働いてうれしい! –

関連する問題