Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android-on-touch监听器被解雇两次_Android_Ontouchlistener - Fatal编程技术网

Android-on-touch监听器被解雇两次

Android-on-touch监听器被解雇两次,android,ontouchlistener,Android,Ontouchlistener,在我的代码中,按钮的ontouch侦听器被触发两次。 请找到下面的代码。我正在使用谷歌API 2.2 java文件中的代码 submit_button = (Button)findViewById(R.id.submit); submit_button .setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View arg0, MotionEvent

在我的代码中,按钮的ontouch侦听器被触发两次。 请找到下面的代码。我正在使用谷歌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;     
                }     
            });

请帮助我解决此问题。

您应该使用onClickListener作为按钮,而不是使用onTouchListener

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

是否将侦听器连接到两个视图元素?在对来自哪个视图的事件检查做出反应之前,请使用
视图arg0
参数。

它会触发两次,因为有一个向下事件和一个向上事件

if分支中的代码始终执行,因为操作被设置为0(顺便说一句,这是MotionEvent.action\u DOWN的值)

也许你想写下面的代码

if(arg1.getAction() == MotionEvent.ACTION_DOWN)
但您真的应该按照Waqas的建议使用OnClickListener

int action = event.getActionMasked();

使用这个。

它有什么作用?它应该如何工作?这类答案没有什么帮助。请提供一些解释,而不仅仅是一行代码。谢谢
int action = event.getActionMasked();