Search code examples
androidgeometrytouch-event

OnTouchEvent update value Issue Android


Hello friends,
I made a game that you need to press a ball and the ball increase his size. Now my problem is that when I call onTouchEvent and calling the function increaseRadius() its update my value when the finger is moving on the screen but if I will put my finger without moving it will update the value once. I want that the value will be updated even if the player put his finger in the same coordinate (Like while loop of updating). The onTouchListener work perfect only if the finger moving, else its work only once.

Here the 'short' code:

public boolean onTouchEvent(MotionEvent event)
{
    if(userball.getRadius()<screenWidth/4)
    {
       userball.increaseRadius();
    }
}
public void increaseRadius()
{
    this.radius+=screenWidth*0.002;
}

Those are the function without the stuff that dont linked to the issue. HOW I WILL CHANGE IT THAT THE BALL WILL UPDATE AND INCREASE HIS SIZE EVEN IF THE PLAYER DOESNT MOVE HIS FINGER?

I want that the value will updated whole the time that the finger of the player is on the screen (Like while loop) on the same coordinate.


Solution

  • Use the if statement to check whether the player only puts his/her finger:

    if (event.getAction() == MotionEvent.ACTION_DOWN) {
    
    }
    

    Similarly, if you want to listen to drag events write your if statement like this:

    if (event.getAction() == MotionEvent.ACTION_MOVE) {
    
    }
    

    In order to have a process going on as long as the user's finger is touching, you can start a thread such as in the following example:

    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        IncreaseSizeThread increaseSizeThread = new IncreaseSizeThread();
    }
    
    if (event.getAction() == MotionEvent.ACTION_UP) {
        increaseSizeThread.stop(); 
        //A better way would be to change a variable that gets the while loop in     
        //the thread going to false e.g. keepGoing = false;
    
    }
    

    And the contents of the thread could be:

    class IncreaseSizeThread extends Thread {
    
        public IncreaseSizeThread() {
        }
    
        void run(){
            while(keepGoing){
                //Size++;
            }
    
        }
    }