1. 程式人生 > >EditText android:imeOptions與inputType="textMultiLine" 的坑

EditText android:imeOptions與inputType="textMultiLine" 的坑

在xml為EditText中設定imeOptions可以控制鍵盤確認鍵的具體功能,如下列舉了一些

android:imeOptions="flagNoExtractUi" //使軟鍵盤不全屏顯示,只佔用一部分螢幕 同時,
這個屬性還能控制元件軟鍵盤右下角按鍵的顯示內容,預設情況下為回車鍵
android:imeOptions="actionNone" //輸入框右側不帶任何提示
android:imeOptions="actionGo"   //右下角按鍵內容為'開始'
android:imeOptions="actionSearch" //右下角按鍵為放大鏡圖片,搜尋
android:imeOptions="actionSend"
//右下角按鍵內容為'傳送' android:imeOptions="actionNext" //右下角按鍵內容為'下一步' 或者下一項 android:imeOptions="actionDone" //右下角按鍵內容為'完成'

坑1 若是多行顯示,會使設定無效

若是設定了inputType="textMultiLine"會使android:imeOptions無效。
可以修改如下屬性
xml中 屬性設定:
1、 將singleLine設定為true(我沒設定也行,但是最終的效果仍然是隻能單行輸入了)
2 、將inputType設定為text
相當於取消了多行顯示的性質

java程式碼設定

editText.setInputType(EditorInfo.TYPE_CLASS_TEXT);
editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);

坑2

問題描述:因為EditText一旦設定了多行顯示,鍵盤總是顯示Enter鍵。有時候我們不僅需要文字輸入多行顯示,而且Enter鍵需要支援imeOptions設定,比如顯示完成鍵而不是回車換行。如這如何做呢?
問題分析以及解決:我們知道,當EditText彈出輸入法時,會呼叫方法
public InputConnection onCreateInputConnection(EditorInfo outAttrs)
來建立和輸入法的連線,設定輸入法的狀態,包括顯示什麼樣的鍵盤佈局。需要注意的地方是這部分程式碼:

if (isMultilineInputType(outAttrs.inputType)) {
     // Multi-line text editors should always show an enter key.
     outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
 }


private static boolean isMultilineInputType(int type) {
        return (type & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) ==
            (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
    }

發現,當EditText的inputType包含textMultiLine標誌位,會強迫imeOptions加上IME_FLAG_NO_ENTER_ACTION位,這導致了只顯示Enter鍵。
解決方法:我們可以繼承EditText類,覆寫onCreateInputConnection方法,如下:

@Overridepublic InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        InputConnection inputConnection = super.onCreateInputConnection(outAttrs);
        if(inputConnection != null){
            outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
        }
        return inputConnection;
    }
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
    InputConnection connection = super.onCreateInputConnection(outAttrs);
    int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION;
    if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) {
        // clear the existing action
        outAttrs.imeOptions ^= imeActions;
        // set the DONE action
        outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
    }
    if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
        outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
    }
    return connection;
}

然後這裡還有一個坑,在基礎EditText後,要重寫完所有的建構函式,要不在inflate時會出錯,直接呼叫父類的相關的構造方法就好。