Android Studio:onTouchEvent要么不运行,要么无法更新变量

时间:2015-04-09 23:05:27

标签: java android android-studio

我一直试图在android studio上编写应用程序,而onTouchEvent似乎并没有更新我的变量。

我的变量在主要活动中定义而不是方法,如下所示:

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 coodinates。像这样

YOU.setY(touchy);
YOU.setX(touchx);

//会得到赏金,但我没有足够的代表。 :/

2 个答案:

答案 0 :(得分:1)

假设您正在尝试回应ImageView中的触摸事件(是的,我认为这是一种可能的路线)。在你的onCreate或onCreateView方法的情况下,你想要向ImageView添加一个OnTouchListener:

myImageView.setOnTouchListener(new View.OnTouchListener(){

@覆盖

public boolean onTouch(View v,MotionEvent event){

touchx = event.getX();

touchy = event.getY();

return true; /* to consume the event */

}

}

那应该为你做。

答案 1 :(得分:1)

您似乎已经实施了onTouchListener&#39; MainActivity中的接口。 那么你需要做的就是这个。只需将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);
}