2011-02-04 8 views
1

사용자 정의 텍스트 뷰를 사용하여 주어진 위치에 주어진 텍스트를 표시하는 데 문제가 있습니다.onDraw는 비 정적 변수에 액세스 할 수 없습니다.

이 코드 사용 N MyTextView 원형 방식으로 배치 만들려 :이 텍스트 뷰, I는 X, Y 좌표를 표시하는 문자열을 전달 연장 내 클래스의 조각

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)); 

} 

을 :

System.out.println("draw x: "+mx+" y: "+my+" text: "+mtext); 
로 된 onDraw는 변수의 콘텐츠에 액세스하지 못할 때문에이 NullPointer를 얻을이 코드
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); 

} 

,

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 

내가 잘못 뭐하는 거지 : 나는 정적과 같은 변수를 정의하면 17,451,515,

나는 (물론) 그들에게 할당 된 마지막 값을 얻을 대신, "0.0 0.0 널 (null)"을 얻을? onDraw가 정적 클래스를 제외한 클래스 변수에 액세스 할 수없는 이유는 무엇입니까?

감사합니다.

+2

당신이 전체'MyTextView' 클래스를 붙여 넣을 수 없습니다 : 나는 당신의 생성자가 줄을 포함 할 필요가 같은데요? – Cristian

답변

0

예외에 관한 질문은 항상 추적 코드를 게시하십시오. 그게 진단 많이 쉽게됩니다.

클래스에 mTextPaint이라는 변수가 있지만 초기화되지 않았습니다. 그 가치는 무엇입니까? 정적으로 초기화되지 않으면 NPE의 원인 일 가능성이 높습니다.

편집는 :

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 해결 방법을 설명하는 데 더 눈에 띄도록 솔루션을 새로운 대답으로 추가해야합니다. 다행 이군! –

관련 문제