在xml為EditText中設定imeOptions可以控制鍵盤确認鍵的具體功能,如下列舉了一些
android:imeOptions="flagNoExtractUi" //使軟鍵盤不全屏顯示,隻占用一部分螢幕 同時,
這個屬性還能控件軟鍵盤右下角按鍵的顯示内容,預設情況下為Enter鍵
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;
}
以上參考的是:http://blog.sina.com.cn/s/blog_97eedec40100wwjd.html
我用的從stackflow抄的代碼:
http://stackoverflow.com/questions/5014219/multiline-edittext-with-done-softinput-action-label-on-2-3
@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) != ) {
// 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) != ) {
outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
}
return connection;
}
然後這裡還有一個坑,在基礎EditText後,要重寫完所有的構造函數,要不在inflate時會出錯,直接調用父類的相關的構造方法就好。