2012-01-18 69 views
0

我正在研究一個應用程序,允許用戶在屏幕上拖動一個點並設置距離值。我想要的是半屏幕的拖動功能,另一半與小工具(按鈕和textViews)。要做到這一點,我創建擴展SurfaceView類,使用位圖「點」和功能的onTouchEvent,在我的xml文件我喜歡下我的看法引用:Android:無法從onTouchEvent動態更新textView文本

<test1.DragView 
     android:id="@+id/view" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
    /> 
<TextView 
      android:id="@+id/textView" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
    /> 

它可以給我我想要的。但現在我想動態更新點的位置。要做到這一點我在我的onTouchEvent函數添加的setText()函數爲我的TextView:

@Override 
public boolean onTouchEvent(MotionEvent event) { 
    x=(int)event.getX(); 
    y=(int)event.getY(); 
    bitmap =BitmapFactory.decodeResource(getResources(), R.drawable.dot); 
    if(x<0) 
     x=0; 
    if(x > width+(bitmap.getWidth()/2)) 
     x=width+(bitmap.getWidth()/2); 
    if(y <0) 
     y=0; 
    if(y > height/2) 
     y=height/2; 
    tv=(TextView) findViewById(R.id.textView); //I declared tv in the beginning of my class 
    tv.setText(x); 
    updateBall(); //it's a function that resets the position of the dot 

    return true; 
} 

它給了我這樣的錯誤

AndroidRuntime(845): FATAL EXCEPTION: main 
AndroidRuntime(845): java.lang.NullPointerException 
AndroidRuntime(845):  
at test1.DragView.onTouchEvent(DragView.java:87) 
AndroidRuntime(845):  
at android.view.View.dispatchTouchEvent(View.java:5462) 
AndroidRuntime(845): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1953) 

我不能用我的TextView在我DragView類。這是正常的嗎?如有需要,我可以提供更多解釋。

編輯: 使用ReubenScratton的解決方案,我現在可以存取權限我的TextView後,但我發現了以下錯誤:

AndroidRuntime(672): FATAL EXCEPTION: main 
AndroidRuntime(672): android.content.res.Resources$NotFoundException: String resource ID #0x109 
AndroidRuntime(672): at android.content.res.Resources.getText(Resources.java:247) 
AndroidRuntime(672): at android.widget.TextView.setText(TextView.java:3427) 
AndroidRuntime(672): at test1.DragView.onDraw(DragView.java:73) 
+3

如果你可以提供一段代碼來調用'setText()'和logcat輸出,那將很方便。 – mdelolmo 2012-01-18 15:26:16

+0

「它給了我像NullPointerException異常」 - 如果你不提供產生NPE的代碼和異常的堆棧跟蹤,你希望我們能夠提供幫助嗎? LogCat至少請 – Guillaume 2012-01-18 15:32:27

+0

@Guillaume你是對的。我編輯了我的問題。 – Anila 2012-01-18 15:33:46

回答

1

我回答我的問題,但請注意,我只是放在一起其他人給出的解決方案(ReubenScrattonlazeR),這樣如果別人有同樣的問題,他會找到整個解決方案。 因此,解決辦法:首先,而不是訪問的我textView直接我有,因爲如果你使用

tv=(TextView)findViewById(); 

您使用View.findViewById()將只能通過子視圖搜索使用

tv=(TextView) ((Activity)getContext()).findViewById(R.id.textView) 

您要使用的Activity.findViewById()ReubenScratton

而對於我的第二個問題,因爲我是直接用一個int到setText()功能也不能正常工作,但由於拉澤的評論我注意到了這一點並找到解決方案。感謝所有幫助我的人:)。