點擊輸入框輸入內容時,輸入完成的時候,想通過直接點擊軟鍵盤中的回車鍵直接收起軟鍵盤,並且發送內容或者搜索內容。
1.首先在xml中設置一個地方,加一個屬性:
<EditText
android:id="@+id/et_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:imeOptions="actionSearch"
android:singleLine="true" />
默認情況下軟鍵盤右下角的按鈕為“下一個”,點擊會到下一個輸入框,設置imeOptions的值為actionSearch、actionDone、actionSend等,軟鍵盤下方變成“搜索”、“完成”、“發送”等。(注:有可能"搜索"不是以文字形式展現的,也許會以一個圖標展現,也就是一個放大鏡圖標,所以如果你的是這樣,別疑惑)
上面只是舉幾個例子,還有的值讀者可以自己去探索試試。
2.接下來就是監聽鍵盤的回車鍵了:
EditText實現setOnEditorActionListener,在onEditAction方法中actionId就對應我們設置的imeOptions。系統默認的actionId有:EditorInfo.IME_NULL、EditorInfo.IME_ACTION_SEND、EditorInfo.IME_ACTION_DONE等。
findViewById(R.id.et_title).setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { //搜索(發送消息)操作(此處省略,根據讀者自己需要,直接調用自己想實現的方法即可)
//收起軟鍵盤
InputMethodManager im = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } return false; } });
在輸入回車的時候也要收起軟鍵盤,此時就稍微開展記錄點軟鍵盤的顯示和隱藏吧
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
// 獲取軟鍵盤的顯示狀態
boolean isOpen = imm.isActive();
// 如果軟鍵盤已經顯示,則隱藏,反之則顯示
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
// 隱藏軟鍵盤
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// 強制顯示軟鍵盤
imm.showSoftInput(getActivity().getCurrentFocus(), InputMethodManager.SHOW_FORCED);
// 強制隱藏軟鍵盤
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);