安卓系统:无法更新text从onTouchEvent动态查看文本



我正在开发一个应用程序,该应用程序允许用户在屏幕上拖动一个点并设置距离值。我想要的是有一半的屏幕用于拖动功能,另一半带有小工具(按钮和文本视图)。为此,我创建了一个扩展SurfaceView的类,使用了位图"点"和函数onTouchEvent,在我的xml文件中,我在视图中引用了以下内容:

 <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函数中为textView添加了setText()函数:

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

我无法在DragView类中使用textView。这正常吗?如果需要,我可以提供更多的解释。

编辑:在使用ReubenScretton的解决方案后,我现在可以访问我的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)

我在回答我自己的问题,但请注意,我只是把其他人给出的解决方案(ReubenScrettonlazeR)放在一起,这样,如果其他人也有同样的问题,他就会找到整个解决方案。因此,解决方案是:首先,我必须使用,而不是直接访问我的textView

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

因为如果你使用

tv=(TextView)findViewById();

您使用的是View.findViewById(),它将只搜索子视图。

您想要使用Activity.findViewById()ReubenScretton

对于我的第二个问题,因为我直接对setText()函数使用int,所以它不起作用,但多亏了lazeR的评论,我注意到了它,并找到了解决方案。感谢所有帮助我的人:)。

最新更新