OnTouchListener not working inside Activity

梦想的初衷 提交于 2019-12-13 04:47:06

问题


so I had some problems with the onTouch method, it didnt do anything, at first i thought something wrogn with the code but then i did this, and it still doesnt work when i touch the screen. Anyone knows what is the problem? Thnx.

{ private FartPianoView fpv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    fpv = new FartPianoView(this);
    setContentView(fpv);
}

@Override
public boolean onTouchEvent(MotionEvent event)
{
    // TODO Auto-generated method stub
    float currentX = event.getX();
    float currentY = event.getY();
    switch(event.getAction())
    {
        case MotionEvent.ACTION_DOWN:
            finish();

            break;
        case MotionEvent.ACTION_UP:
            finish();
            break;
    }
    return false;
}

}


回答1:


You need to override the

public boolean onTouchEvent (MotionEvent e)

method of the Activity class, not the method you are overriding (onTouch(...) of the OnTouchListener). Then it should work. Example:

@Override
public boolean onTouchEvent(MotionEvent e) {

    // do your stuff...

    return false;
}

This means you are recognizing touch events on the Activity, not on the View. If you want to explicitly detect touches on the View via OnTouchListener, you need to set the OnTouchListener for your View.

In your case:

fpv = new FartPianoView(this);
fpv.setOnTouchListener(this);


来源:https://stackoverflow.com/questions/24471188/ontouchlistener-not-working-inside-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!