Pr.Pg Next Pg

Motion Events and Motion Actions tutorials

  • We are now going to make modifications to our application.

  • When we click on the icon and drag it to another position we will put another icon at the former position.

  • In order to do so modify the onTouch() and run() method as follows..

 

 

 

public boolean onTouch(View arg0, MotionEvent arg1) {

// TODO Auto-generated method stub

x = arg1.getX();

y = arg1.getY();

if(arg1.getAction() == MotionEvent.ACTION_DOWN){

x2=arg1.getX();

y2=arg1.getY();

}

return true;

}

public void run() {

// TODO Auto-generated method stub

while(running){

if(!holder.getSurface().isValid())

continue;

Canvas mycanvas = holder.lockCanvas();

mycanvas.drawRGB(120, 254, 36);

if(x!=0&&y!=0){

bm=BitmapFactory.decodeResource(getResources(), R.drawable.extra);

mycanvas.drawBitmap(bm, x-bm.getWidth()/2, y-bm.getHeight()/2, null);

}

if(x2!=0&&y2!=0){

bm=BitmapFactory.decodeResource(getResources(), R.drawable.extra2);

mycanvas.drawBitmap(bm, x2-bm.getWidth()/2, y2-bm.getHeight()/2, null);

}

holder.unlockCanvasAndPost(mycanvas);

}

}

 

 

  • In this case the variables x2 and y2 store the last position from where are icon image extra was moved and adds the new icon named extra2 there.

  • Below are the few commonly used MotionEvent Actions:

ACTION_CANCEL

  • The current gesture has been aborted.

ACTION_DOWN

  • A pressed gesture has started, the motion contains the initial starting location.

ACTION_UP

  • A pressed gesture has finished, the motion contains the final release location as well as any intermediate points since the last down or move event.

ACTION_SCROLL

  • The motion event contains relative vertical and/or horizontal scroll offsets.

ACTION_MOVE

  • A change has happened during a press gesture (between ACTION_DOWN andACTION_UP).

 

Pr.Pg border                                              Next Pg