Android - on the listener twice

In my ontouch code, the button listener starts twice. code below. 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 solve this problem.

+5
source share
4 answers

instead of 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(); } }); 
+7
source

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

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

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

Perhaps you wanted to write the following code instead?

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

But you really should use the OnClickListener as Wakas suggested.

+14
source

Did the listener attach two to view items? Before reacting to checking the event from which it comes using the View arg0 parameter.

0
source
 int action = event.getActionMasked(); 

Use this.

0
source

Source: https://habr.com/ru/post/885791/


All Articles