2012-02-14 30 views
2

我需要監聽事件上的EditText如何在android上捕獲KeyEvents?

  1. 當用戶開始輸入
  2. 和丟失焦點時

我嘗試這樣做,這是行不通的。我錯了什麼?

etTo.setOnKeyListener(new OnKeyListener(){ 

    public boolean onKey(View v, int keyCode, KeyEvent event) { 
     if(event.getAction() ==KeyEvent.ACTION_DOWN){ 
      etTo.setText(""); 
     } 
    return false; 
    }   
}); 
+0

重複問題... http://stackoverflow.com/questions/904376/android-key-event-problem – himanshu 2012-02-14 12:51:21

回答

1

對於第一個,你可以試試這個:

myEditText.addTextChangedListener(new TextWatcher() { 
public void afterTextChanged(Editable s) { 
    //do something 
} 

    public void beforeTextChanged(CharSequence s, int start, int count, int after){ 
    //do something 
} 

public void onTextChanged(CharSequence s, int start, int before, int count) { 
    //do something 
} 
}); 

的第二個嘗試:

 myEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { 
    @Override 
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
     if (actionId == EditorInfo.IME_ACTION_DONE) { 

      yourcalc(); 

      return true; 
     } 
     return false; 
    } 
}); 
1

嘗試使用

etTo.setOnFocusChangeListener(new OnFocusChangeListener() { 

      @Override 
      public void onFocusChange(View v, boolean hasFocus) { 
       // TODO Auto-generated method stub 

      } 
     }); 

檢查重點,

etTo.addTextChangedListener(new TextWatcher() { 

      @Override 
      public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { 
       // TODO user start to typing text 

      } 

      @Override 
      public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, 
        int arg3) { 
       // TODO cursor is into the EditText 

      } 

      @Override 
      public void afterTextChanged(Editable arg0) { 
       // TODO Auto-generated method stub 

      } 
     });