一志秃、改變回車按鈕
在使用鍵盤輸入的時候,有時我們可以看到回車鍵是“下一步”嚼酝、“搜索”、“確認(rèn)”等,那么這個效果要怎么做呢灾测?其實(shí)很簡單流椒,我們只需要在EditText中設(shè)置imeOptions這個屬性就行了,下面我們只用搜索舉例涎跨,其他方式套路一樣洼冻,自己改變下參數(shù)就行。
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionSearch"
android:singleLine="true"/>
或者
//自己可以替換其他常量實(shí)現(xiàn)不同功能
editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
editText.setSingleLine();
二六敬、常見屬性
屬性 | 常量 | 描述 |
---|---|---|
actionNext | EditorInfo.IME_ACTION_NEXT | 下一步碘赖,用于跳轉(zhuǎn)到下一個EditText |
actionGo | EditorInfo.IME_ACTION_GO | 前往,用于打開鏈接外构。 |
actionSend | EditorInfo.IME_ACTION_SEND | 發(fā)送普泡,用于發(fā)送信息 |
actionSearch | EditorInfo.IME_ACTION_SEARCH | 搜索,用于搜索信息 |
actionDone | EditorInfo.IME_ACTION_DONE | 確認(rèn)审编,表示完成 |
actionUnspecified | EditorInfo.IME_ACTION_UNSPECIFIED | 未指定 |
actionNone | EditorInfo.IME_ACTION_NONE | 沒有動作 |
三撼班、監(jiān)聽回車鍵的事件
方法一:
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//是否是回車鍵
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// 自己處理業(yè)務(wù)邏輯
}
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);
// 自己處理業(yè)務(wù)邏輯
}
return false;
}
});
補(bǔ)充部分
點(diǎn)擊時執(zhí)行兩次監(jiān)聽事件的問題:
默認(rèn)onkey事件包含了down和up事件,所以會出現(xiàn)執(zhí)行兩次的情況勘究,上加event.getAction() == KeyEvent.ACTION_DOWN判斷就行了矮湘,當(dāng)然判斷up也可以。