記錄一下如何把軟鍵盤的回車按鍵變成搜索按鍵
這個(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);
}