synthesis
synthesis

Reputation: 95

android: Activity starts 2 times with OnTouchListener()

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()

Upvotes: 3

Views: 820

Answers (3)

Cat
Cat

Reputation: 67522

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()

Upvotes: 4

K_Anas
K_Anas

Reputation: 31466

You hould handle the ACTION_DOWN event.

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

// Do Something
}
return true;

Upvotes: 0

alex
alex

Reputation: 11410

I think it is being called on both onKeyUp() and onKeyDown() - and these are the methods you should override, not onTouch().

EDIT:

I didn't read carefully enough - you're after long clicks, I didn't get it at first. I once received a great answer to similar question. Take a look: How to access menu button on long click.

Upvotes: 0

Related Questions