Android - on touch listener两次开火

Pre*_*rem 6 android ontouchlistener

在我的代码中,按钮的ontouch侦听器被触发两次.请在下面找到代码.我使用的是Google API 2.2.

java文件中的代码....

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;     
                }     
            });
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题.

Mad*_*ink 15

它发射两次因为有一个向下事件和一个向上事件.

if分支中的代码总是执行,因为action设置为0(顺便说一下,它是MotionEvent.ACTION_DOWN的值).

int action=0;
if(action == MotionEvent.ACTION_DOWN)
Run Code Online (Sandbox Code Playgroud)

也许你打算写下面的代码呢?

if(arg1.getAction() == MotionEvent.ACTION_DOWN)
Run Code Online (Sandbox Code Playgroud)

但是你应该像Waqas建议的那样使用OnClickListener.


waq*_*lam 8

而是采用onTouchListener,你应该使用onClickListener的按钮.

submit_button.setOnClickListener(new OnClickListener() {    
    public void onClick(View v) {
        startActivity(new Intent(First_Activity.this, Second_Activity.class));
        finish();
    }
});
Run Code Online (Sandbox Code Playgroud)