问题
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