一般情況下我們的輸入框都需要一些這樣的需求:
幸運的是EditText給我們預留了一個回調接口:setOnEditorActionListener
<pre name="code" class="java">EditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEND) {
//要做的事
}
return false;
}
});
actionNone : 回車鍵,按下後光標到下一行
actionSend : Send
actionNext : Next
actionDone : Done,隱藏軟鍵盤,即使不是最後一個文本輸入框
actionSearch : search 搜索
注意一定要設置android:singleLine="true",否則回車會換行
<EditText
---
android:imeOptions="actionSearch"
android:singleLine="true" >
</EditText>
2、監聽
mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//當actionId == XX_SEND 或者 XX_DONE時都觸發
//或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN時也觸發
//注意,這是一定要判斷event != null。因爲在某些輸入法上會返回null。
if (actionId == EditorInfo.IME_ACTION_SEND
|| actionId == EditorInfo.IME_ACTION_DONE
|| (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
//處理事件
}
return false;
}
});