I am playing with a game on Android, and I have a function MoveCharacter (int direction) that moves an animated sprite when buttons are pressed
For example, when user presses up I have this code:
mControls.UpButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mLevel.mCharAnimation.FrameUp();
}
});
However, I’d like to be able to keep moving the character as long as the user keeps the button down. Surprisingly, I have not found out how to do this in Android. Is there some kind of onButtonDownLister?
ImageButton myButton = (ImageButton) findViewById(R. id. epic_button); if (myButton. isEnabled()){ //then the button is enabled. }
OnClickListener and wires the listener to the button using setOnClickListener(View. OnClickListener) . As a result, the system executes the code you write in onClick(View) after the user presses the button. The system executes the code in onClick on the main thread.
To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
this is how your code should look like: public class main extends AppCompatActivity { TextView t; TextView A; TextView B; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R. layout. your_layout); // THIS IS VERY IMPORTANT t = (TextView) findViewById(R.
You need to use an OnTouchListener to have separate actions for down, up, and other states.
mControls.UpButton.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Do something
return true;
case MotionEvent.ACTION_UP:
// No longer down
return true;
}
return false;
}
});
As mentioned in the comments by Gary Bak you would want to detect if the user drags their finger outside the button also.
mButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Pressed down
return true;
case MotionEvent.ACTION_UP:
// Released
return true;
case MotionEvent.ACTION_CANCEL:
// Released - Dragged finger outside
return true;
}
return false;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With