Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - how to check whether the screen is being touched?

Tags:

android

input

I am currently using onTouchEvent(MotionEvent me) to register input events, however, this being a game app, when the frame rate slows down the program sometimes fails to register an input.UP event after a GUI button has been released, which causes my character to keep moving on its own...

Is there like a boolean method in the API that checks for whether there is a finger on the screen at any given time?

Thank you

like image 707
Alex Avatar asked Jan 19 '12 22:01

Alex


2 Answers

Might be worth checking out the documentation for onUserInteraction().

Something like this would allow you to know how recently the user has interacted with the screen:

@Override
public void onUserInteraction(){
    MyTimerClass.getInstance().resetTimer();
}
like image 69
Graham Avatar answered Oct 06 '22 14:10

Graham


You can get the on touch event and see if Action down, Move or Action Up and other actions but for the moment let us stop here. I have a simple example that I think you or anyone else will find it usefull.

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;

public class MainActivity extends Activity {

    private boolean isTouch = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int X = (int) event.getX();
        int Y = (int) event.getY();

        int eventaction = event.getAction();
        switch (eventaction) {

        case MotionEvent.ACTION_DOWN:
            Toast.makeText(this, "ACTION_DOWN AT COORDS "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();         
            isTouch = true;
            break;

        case MotionEvent.ACTION_MOVE:
            Toast.makeText(this, "MOVE "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
            break;

        case MotionEvent.ACTION_UP:
            Toast.makeText(this, "ACTION_UP "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
            break;
        }
        return true;
    }
}

Cheers,

like image 2
MSA Avatar answered Oct 06 '22 15:10

MSA