Android項(xiàng)目中要實(shí)現(xiàn)這樣一個(gè)需求晃择,在搜索框中輸入關(guān)鍵詞,在手機(jī)彈出的軟鍵盤中也物,回車鍵變?yōu)樗阉麈I宫屠,點(diǎn)擊搜索鍵執(zhí)行搜索。
1滑蚯、修改EditText屬性:
<EditText
android:id="@+id/et_search"
android:layout_width="100dp"
android:layout_height="25dp"
android:textSize="12sp"
android:hint="請(qǐng)輸入關(guān)鍵詞"
android:imeOptions="actionSearch"
android:singleLine="true"/>
android:imeOption="actionSearch"的作用是將回車兩字改為搜索浪蹂,
android:singleLine="true"的作用是防止搜索框換行抵栈。
2、 點(diǎn)擊時(shí)執(zhí)行兩次監(jiān)聽事件的問題:
執(zhí)行上述代碼我發(fā)現(xiàn)每次點(diǎn)擊搜索都會(huì)執(zhí)行兩次搜索方法坤次,后來發(fā)現(xiàn)時(shí)忘了沒有加event.getAction() == KeyEvent.ACTION_DOWN這句判斷古劲。
修改代碼如下:
OnKeyListener事件:
et_search=(EditText)findViewById(R.id.et_search);
et_search.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(SearchActivity.this.getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//搜索
search();
}
return false;
}
});