Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - on touch listener fired twice

In my code, ontouch listener of a button is fired twice. please find below the code. I am using Google API 2.2.

Code in java file ....

submit_button = (Button)findViewById(R.id.submit);

 submit_button .setOnTouchListener(new View.OnTouchListener()
        {       
            public boolean onTouch(View arg0, MotionEvent arg1) { 
                int action=0;
                if(action == MotionEvent.ACTION_DOWN)
                {                   

                    startActivity(new Intent(First_Activity.this, Second_Activity.class));
                    finish(); 
                }
                return true;     
                }     
            });

Please help me on solving this issue.

like image 854
Prem Avatar asked Mar 03 '12 17:03

Prem


3 Answers

It fires twice because there is a down event and an up event.

The code in the if branch always executes since the action is set to 0 (which, incidentally, is the value of MotionEvent.ACTION_DOWN).

int action=0;
if(action == MotionEvent.ACTION_DOWN)

Maybe you meant to write the following code instead?

if(arg1.getAction() == MotionEvent.ACTION_DOWN)

But you really should use OnClickListener as Waqas suggested.

like image 176
Madis Pink Avatar answered Nov 20 '22 01:11

Madis Pink


instead of using onTouchListener, you should use onClickListener for buttons.

submit_button.setOnClickListener(new OnClickListener() {    
    public void onClick(View v) {
        startActivity(new Intent(First_Activity.this, Second_Activity.class));
        finish();
    }
});
like image 21
waqaslam Avatar answered Nov 20 '22 01:11

waqaslam


Did you attach the listener two to view elements? Before reacting on the event check from which view it comes using the View arg0 parameter.

like image 1
Flo Avatar answered Nov 19 '22 23:11

Flo