Search code examples
javaandroidtimerontouch

Activate after long touch and release. Android java app


First app ever for me, and first time experiencing with java coding.

I'm building an app for assisting my Rubiks cube speed training, and i'm stuck on my timer.

My general plan is:

I have my main activity screen, where with 1 touch (anywhere on the screen except my 2 buttons) can start a timer. When the timer starts the buttons will fade, and only the timer is visible. At this moment I have my MainActivity, and a Timer activity. When pressing the screen the timer activity "launches". I then have to press once more to start the timer, this is ok for now, I will fix it somewhat later.

My main goal for now is:

On the timer activity, I want to press and HOLD for at least 2 seconds, and THEN upon release, the timer must start. Hereafter, with a new click, the timer must stop.

I have searched, but it is difficult with minimum knowledge. I have tried a few different things. And what I have is basically something like this.

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

    TimerView = (TextView) findViewById(R.id.TextTimerView);


    View StopTimeView = (View) findViewById(R.id.StopTimeView);

    StopTimeView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                starttime = SystemClock.uptimeMillis();
                timerhandler.postDelayed(timerrunnable,2000);
                timestarted =  true;
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if(timestarted = true){
                    timestarted = false;
                    timerhandler.removeCallbacks(timerrunnable);

                }
            }

            return true;
        }
    });

}

This code stops when the touch is released. If I remove the last IF sentence, the timer automatically starts after the given 2 seconds, no matter if I hold or not. Furthermore, I need to add an additional button to stop the timer, which I do not want (the ability to be able to stop by touching everywhere is important).

I hope the question is understandable and not to vague. If more of the code is needed, please let me know. Thanks for your time!


Solution

  • Simply check in your timerrunnable if the button is still pressed. Also, start the onTouch method with a check whether your timer is running. If it is, you know you want to stop it - if it isn't, you can continue with the code you already have.