Android EditText 實(shí)現(xiàn)軟鍵盤搜索按鈕

記錄一下如何把軟鍵盤的回車按鍵變成搜索按鍵
這個(gè)估計(jì)大部分人也經(jīng)常用的到

這個(gè)直接xml文件設(shè)置 EditText 三個(gè)屬性

android:imeOptions="actionSearch"
android:singleLine="true"
android:maxLines="1"

網(wǎng)上有些直接用 android:imeOptions="actionSearch"
這樣是不夠的 而 android:maxLines="1"這個(gè)是為了防止點(diǎn)擊回車鍵換行,我個(gè)人認(rèn)為也是有必要的

<EditText
    android:id="@+id/search_input"
    android:background="#00000000"
    android:layout_width="30dp"
    android:layout_height="match_parent"
    android:ellipsize="end"
    android:hint="搜索"
    android:imeOptions="actionSearch"
    android:singleLine="true"
    android:maxLines="1"
    android:textSize="15sp" />

然后需要監(jiān)聽軟鍵盤的搜索然后

EditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //點(diǎn)擊搜索的時(shí)候隱藏軟鍵盤
                    hideKeyboard(EditText);
                    // 在這里寫搜索的操作,一般都是網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)
                    return true;
                }
 
                return false;
            }
        });

        /**
     * 隱藏軟鍵盤
     * @param context :上下文
     * @param view    :一般為EditText
     */
    public void hideKeyboard(View view) {
        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容