Android 修改軟鍵盤上的回車鍵功能,用改變成搜索按鈕舉例

一、改變回車按鈕

在使用鍵盤輸入的時候,有時我們可以看到回車鍵是“下一步”、“搜索”、“確認”等,那么這個效果要怎么做呢?其實很簡單,我們只需要在EditText中設置imeOptions這個屬性就行了,下面我們只用搜索舉例,其他方式套路一樣,自己改變下參數就行

<EditText  
    android:layout_width="match_parent"  
    android:layout_height="wrap_content"  
    android:imeOptions="actionSearch"  
    android:singleLine="true"/>  

或者

//自己可以替換其他常量實現不同功能
editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
editText.setSingleLine();

二、常見屬性

屬性 常量 描述
actionNext EditorInfo.IME_ACTION_NEXT 下一步,用于跳轉到下一個EditText
actionGo EditorInfo.IME_ACTION_GO 前往,用于打開鏈接。
actionSend EditorInfo.IME_ACTION_SEND 發送,用于發送信息
actionSearch EditorInfo.IME_ACTION_SEARCH 搜索,用于搜索信息
actionDone EditorInfo.IME_ACTION_DONE 確認,表示完成
actionUnspecified EditorInfo.IME_ACTION_UNSPECIFIED 未指定
actionNone EditorInfo.IME_ACTION_NONE 沒有動作

三、監聽回車鍵的事件

方法一:
 editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //是否是回車鍵  
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                     // 自己處理業務邏輯
                }
                return false; //返回true,保留軟鍵盤。false,隱藏軟鍵盤
            }
        });
方法二:
editText.setOnKeyListener(new View.OnKeyListener() {  
    @Override  
    public boolean onKey(View v, int keyCode, KeyEvent event) {  
        //是否是回車鍵  
        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                  //隱藏軟鍵盤  
                  ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                 
                   // 自己處理業務邏輯

         }
        return false;  
    }  
});  
補充部分

點擊時執行兩次監聽事件的問題:
默認onkey事件包含了down和up事件,所以會出現執行兩次的情況,上加event.getAction() == KeyEvent.ACTION_DOWN判斷就行了,當然判斷up也可以。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容