2012-02-15 114 views
5

我有一个EditText。我wamt做一些事情,当用户按输入密钥,同时更改EditText。我怎样才能做到这一点?如何收听EditText?

最简单的方法:

final EditText edittext = (EditText) findViewById(R.id.edittext); 
edittext.setOnKeyListener(new OnKeyListener() { 
    public boolean onKey(View v, int keyCode, KeyEvent event) { 
     // If the event is a key-down event on the "enter" button 
     if ((event.getAction() == KeyEvent.ACTION_DOWN) && 
      (keyCode == KeyEvent.KEYCODE_ENTER)) { 
      // Perform action on key press 
      Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show(); 
      return true; 
     } 
     return false; 
    } 
}); 
+0

好的,我该如何比较CharSequence和Key Enter? – ruslanys 2012-02-15 23:00:40

回答

5

示例代码文本观察者

your_edittext.addTextChangedListener(new InputValidator()); 

    private class InputValidator implements TextWatcher { 

     public void afterTextChanged(Editable s) { 

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

     }  
     public void onTextChanged(CharSequence s, int start, int before, 
       int count) { 

     }  
    }  
} 
-2
your_edittext.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     //do something 
    } 

}); 
+0

不,它不起作用。当用户在EditText中键入一些文本时,我需要在键盘上听取按键ENTER。我不在乎用户何时会触摸屏幕。 – ruslanys 2012-02-15 22:37:47

0

您需要使用TextWatcher用于此目的。这里是一个关于如何使用TextWatcher和Android textwatcher API的例子。

+0

哦,是啊!非常感谢你。这是一个很好的决定。 – ruslanys 2012-02-15 22:40:04

4

首先,创建一个OnEditorActionListener(作为私有实例变量,例如):

private TextView.OnEditorActionListener mEnterListener = 
    new TextView.OnEditorActionListener() { 
     @Override 
     public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
      if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) { 
       /* If the action is a key-up event on the return key, do something */ 
      } 
     return true; 
    }); 

然后,设置监听器(即,在您的onCreate法):

EditText mEditText = (EditText) findViewById(...); 
mEditText.setOnEditorActionListener(mEnterListener); 
+0

有一个关于如何在'BluetoothChat'示例代码中隐藏的示例:http://developer.android.com/resources/samples/BluetoothChat/src/com/example/android/BluetoothChat/BluetoothChat.html – 2012-02-15 22:41:30

+0

该方法比以前更难,无论如何谢谢。 – ruslanys 2012-02-15 22:42:21

+0

对不起,你的方法更好。谢谢) – ruslanys 2012-02-15 23:13:33

1

另一种选择是:

your_edittext.addTextChangedListener(new TextWatcher() { 

     @Override 
     public void afterTextChanged(Editable s) {} 

     @Override  
     public void beforeTextChanged(CharSequence s, int start, 
     int count, int after) { 
     } 

     @Override  
     public void onTextChanged(CharSequence s, int start, 
     int before, int count) { 

     } 
     });