2013-03-09 68 views
2

下面的代碼:Android:爲什麼onTouchListener()打開多個警報對話框?

 textView1.setOnTouchListener(new View.OnTouchListener() { 
     public boolean onTouch(View v, MotionEvent event) { 
      String content = textView1.getText().toString(); 
      if (!content.equals("")){ 
       showNameDialog(); 
      } 
      return true; 
     } 
    }); 

很簡單。如果字符串內容中有文本,它將執行showNameDialog()方法。

這裏的方法:

private void showNameDialog() { 
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this); 
    dialogBuilder.setTitle(name.toString().toUpperCase()); 
    dialogBuilder.setMessage("Name's frequency: " + arrayListToString); 
    dialogBuilder.setPositiveButton("ok", null); 
    AlertDialog alertDialog = dialogBuilder.create(); 
    alertDialog.show(); 
    } 

這一切都工作得很好,除了當我點擊textView1,它打開兩個,三個或四個AlertDialogs的事實。爲什麼?我怎樣才能讓它只打開一個?

回答

4

觸摸不是點擊,所以我認爲onTouch可以在觸摸視圖(觸摸,然後觸摸等)時多次調用。相反,嘗試使用OnClickListener:

textView1.setClickable (true); 
textView1.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      String content = textView1.getText().toString(); 
      if (!content.equals("")){ 
       showNameDialog(); 
      } 
     } 
    }); 
+1

謝謝你的回答!它的工作原理,但它只能從第二次點擊。這是一種常見的行爲? – 2013-03-09 19:10:59

+0

輔助點擊是什麼意思?在屏幕上只能用手指點擊一下,對吧? – Dayerman 2013-03-09 19:19:29

+0

@EricsonWillians如果有這樣的屬性android:focusableInTouchMode =「true」,請檢查您的xml佈局文件。如果元素在觸摸模式下可以聚焦,它將首先獲得焦點,然後執行點擊。 – andrew 2013-03-09 19:20:47

3

嘗試使用此代碼

textView1.setOnTouchListener(new View.OnTouchListener() { 
    public boolean onTouch(View v, MotionEvent event) { 
     String content = textView1.getText().toString(); 
      if(event.getAction() == MotionEvent.ACTION_DOWN){ 
       if (!content.equals("")){ 
          showNameDialog(); 
        } 
      } 
     return true; 
    } 
}); 
+1

它完美的工作!它只打開一個,它在第一次點擊時工作,就是我想要的。 – 2013-03-09 19:23:07

+0

不客氣。 – AwadKab 2013-03-09 19:32:36