Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: Activity starts 2 times with OnTouchListener()

Tags:

android

I've a motion class for a longer pressed_state button. It works really fine!

But does anybody knows why in this code block my activity is starting 2 times? When i'm pressing the back button, i've to do this 2 times.

Thx for any help!


This is my java code:

   Button MenuBtnStart;  

   final Handler handlerBtnStart = new Handler();

          MenuBtnStart.setOnTouchListener(new OnTouchListener() {
          public boolean onTouch(final View v, MotionEvent event) {

          MenuBtnStart.setBackgroundDrawable(getResources().getDrawable(R.drawable.hover));

                 v.setPressed(true);

                 handlerBtnStart.postDelayed(new Runnable() {

                           public void run() {

                            Intent myIntent = new Intent(TextActivity.this, NextActivity.class);
                            TextActivity.this.startActivity(myIntent);

                        v.setPressed(false);

                    }

                }, 900);  // end of Handler new Runnable()

                 return true;
          } 

 });  // end of OnTouchListener()
like image 583
synthesis Avatar asked Jan 27 '26 18:01

synthesis


1 Answers

You should only be activating it if the action is DOWN; there may be a MOVE or UP action after this, which would activate it a second time.

final Handler handlerBtnStart = new Handler();

MenuBtnStart.setOnTouchListener(new OnTouchListener() {

    public boolean onTouch(final View v, MotionEvent event) {
        int action = event.getAction() & MotionEvent.ACTION_MASK;

        if (action == MotionEvent.ACTION_DOWN) { 
            MenuBtnStart.setBackgroundDrawable(getResources().getDrawable(R.drawable.hover));

            v.setPressed(true);

            handlerBtnStart.postDelayed(new Runnable() {

                public void run() {

                    Intent myIntent = new Intent(ThisActivity.this, NextActivity.class);
                    ThisActivity.this.startActivity(myIntent);

                    v.setPressed(false);

                }

            }, 900);  // end of Handler new Runnable()

            return true;
        }

        return false;
    }

});  // end of OnTouchListener()
like image 132
Cat Avatar answered Jan 30 '26 08:01

Cat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!