我一直在尝试在 android studio 上编写一个应用程序,但 onTouchEvent 似乎没有更新我的变量。
我的变量是在主 Activity 中定义的,而不是方法,如下所示:
public float touchy;
public float touchx;
我的 onTouchEvent 代码如下:
public boolean onTouchEvent(MotionEvent event) {
touchx = (float) 200.0;//event.getX(); ive tried to just put solid numbers
touchy = (float) 200.0;//event.getY(); but even that doesnt seem to work
return true;
}
这在我的图像按钮“movecircle”中进行了测试(是的,它运行了)
public void MoveCircleOnClick(View view) {
if (touchx >0){
YOU.setY(50);//<<<this is to see if there is a result: there isnt
}
我的目标是当 MoveCircleOnClick 运行时,您(imageview)将被传输到 touchx 和 touchy 坐标。像这样
YOU.setY(touchy);
YOU.setX(touchx);
//会赏金,但我没有足够的代表。 :/
最佳答案
看来您在 MainActivity 中实现了“onTouchListener”接口(interface)。 那么你需要做的就是这个。只需将您的 MainActivity 设置为 imageview 的 onTouchListener 即可。
public class MainActivity implements OnTouchListener {
...
@Override
public boolean onTouch(View v, MotionEvent event) {
touchx = (float) 200.0;//event.getX(); ive tried to just put solid numbers
touchy = (float) 200.0;//event.getY(); but even that doesnt seem to work
return true;
}
...
}
在 OnCreate() 中,
@Override
public void OnCreate(){
...
// get ImageView instance like this.
ImageView YOU = (ImageView) findViewById(R.id.imageviewId);
...
// And set it.
YOU.setOnTouchListener(this);
}
关于java - Android Studio : onTouchEvent either doesn't run or can't update variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29550561/