天天看點

探究 Android 調用軟鍵盤搜尋,setOnKeyListener 事件執行兩次

一、EditText調用軟鍵盤搜尋 setOnKeyListener 事件為什麼執行了兩次?

etProjectName.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_ENTER) {
        // 先隐藏鍵盤
        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
            .hideSoftInputFromWindow(PublishProjectActivity.this.getCurrentFocus()
                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        //進行搜尋操作的方法,在該方法中可以加入mEditSearchUser的非空判斷
        **search();     //執行兩次,想一想為什麼?**
        return true;
    }
    return false;
    }
});
           

二、解決方案:

方案1

mBinding.etSearch.setOnKeyListener((v, keyCode, event) -> {        // 開始搜尋
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) { //避免setOnKeyListener 執行兩次
                // 先隐藏鍵盤
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus()
                                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                //搜尋邏輯
                search(mBinding.etSearch.getText().toString());
                return true;
            }
            return false;
        });
           

方案2

et.setOnEditorActionListener(new TextView.OnEditorActionListener() { 
    @Override 
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event){ 
        //判斷是否是“放大鏡”鍵【簡稱搜尋鍵】
        if(actionId == EditorInfo.IME_ACTION_SEARCH){ 
        //隐藏軟鍵盤 
        //對應邏輯操作
        return true; 
        } 
        return false; 
    } 
});
           
總結:setOnEditorActionListener這個方法,并不是在我們點選EditText的時候觸發,也不是在我們對EditText進行編輯時觸發,而是在我們編輯完之後點選軟鍵盤上的各種鍵才會觸發

三、知識拓展

1、修改Editview屬性:Android:imeOptions=“actionSearch” 在該Editview獲得焦點的時候将“回車”鍵改為“搜尋”

android:singleLine="true"      不然回車【搜尋】會換行
可以随自己的需求更改軟鍵盤右下角的顯示樣式,例如:搜尋,下一步,Q(搜尋圖示)

actionNone : 按下後光标到下一行(回車)
actionGo : 按下後搜尋(Go)
actionSearch : 放大鏡【搜尋】
actionSend : Send 按下後發送
actionNext : Next 下一步
actionDone : Done,确定/完成,隐藏軟鍵盤(包括不是最後一個文本輸入框的情況也會隐藏)
使用方法:在xml裡面寫布局時直接加給EditTxt的imeOptions屬性,例如:

項目開發中涉及到按鍵事件處理:

**“dispatchKeyEvent” “onKeyDown ”“onKeyLisenter” 簡單了解**
接受按鍵優先級:

**dispatchKeyEvent > Activity的onKeyDown > view的onKeyLisenter**
其中按鍵處理事件return true ;表示已消耗此事件,不再繼續傳遞;
           

2、Android MotionEvent的getX()和getRawX()方法的差別

3、Android中的View:getLeft()、getTop()、getRight()、getBottom()​​​​​​​

此博文主要參閱:https://blog.csdn.net/m0_37700275/article/details/76944153,想了解更多類似的知識點,可以點選此連結!

繼續閱讀