Drawable's movement with buttons

I've been learning android for almost a month, and I want to make a simple game with a custom class that extends from View, and it's included on main_activity.xml. In Main Activity.class I create an instance of the View, and control the movement of the sprite on the GameView with buttons, so each button has a method that control sprite's movement like this:

public void move_up(View v){ gameview.sprite.move(Dir.UP);}

The problem is that it only works when the button is released, and it's executed one time. I want the method to be executed while the botton is pressed but I can't figure out how to do this.

-------------Problems Reply------------

I'm assuming by the name of your method that you're adding the onClick property to the xml layout file in order to handle the event. While this may seem convenient at first it will not give you what you need.

Instead, you should implement the OnTouchListener which gives you information about what touch event is currently happening, in your case you'd want to handle the ACTION_DOWN action:

findViewById(R.id.btn_up).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
gameview.sprite.move(Dir.UP); //Or whatever
return true; //In case you wan to handle ACTION_UP
}
return false;
}
});

Although you could make your Activity implement the listener and handle multiple buttons there. This is achieved simply by telling your activity to implement OnTouchListener, imeplementing the method onTouch as in the code above but instead as a method of your activity.

And the resulting set, would be simplified to findViewById(R.id.btn_up).setOnTouchListener(this); where R.id.btn_up is the id you've defined in the xml file.

This would make it start moving when they press, instead of when they release, if what you want is to make it move until they release (which would make sense), do something like:

if(event.getAction() == MotionEvent.ACTION_DOWN){
gameview.sprite.move(Dir.UP); //Or whatever
return true; //In case you wan to handle ACTION_UP
}else
if(event.getAction() == MotionEvent.ACTION_UP){
gameview.sprite.stop(); //Or whatever you call the stop method
return false;
}

Category:android Views:2 Time:2018-03-10
Tags: button android

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.101 (s). 11 q(s)