2012-03-03 162 views
5

在我的代碼中,一個按鈕的ontouch偵聽器被觸發兩次。 請在下面找到代碼。我正在使用Google API 2.2。Android - 觸摸監聽器被觸發兩次

在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;  
       }  
      }); 

請幫我解決這個問題。

回答

7

而不是使用onTouchListener,你應該使用onClickListener按鈕。

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

感謝它的工作。 – Prem 2012-03-03 19:34:30

0

您是否附加了偵聽器二來查看元素?在使用View arg0參數進行事件檢查之前,從哪個視圖進行響應。

14

由於存在停機事件和停機事件,所以會觸發兩次。

由於動作設置爲0(順便說一句,是MotionEvent.ACTION_DOWN的值),因此if分支中的代碼始終執行。

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

也許你打算寫下面的代碼呢?

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

但是你作爲Waqas建議真的應該使用OnClickListener。

+0

真的很有幫助,非常感謝。 – katzenhut 2014-02-24 13:24:04

0
int action = event.getActionMasked(); 

使用此。

+3

它做什麼?它應該如何工作?這種答案是沒有幫助的。請提供一些解釋,而不僅僅是一行代碼。謝謝 – katzenhut 2014-02-24 13:20:13