Android软键盘显示“搜索”

效果预览

布局属性

    首先需要在EditText的布局中插入android:imeOptions=”actionSearch”和android:inputType=”text”属性,使键盘右下角显示搜索按钮

1
2
3
4
5
6
7
8
9
10
11
12
13
<EditText
android:hint="新闻搜索"
android:id="@+id/edit_newsSearch"
android:inputType="text"
android:lines="1"
android:imeOptions="actionSearch"
android:layout_marginTop="10dp"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_width="match_parent"
android:layout_height="48dp"/>

注意:这里一定不要添加android:maxLength=”1”,添加后会无视android:imeOptions=”actionSearch”的效果

程序实现

    然后在java代码中给软键盘添加监听事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//    给键盘添加监听
edit_newsSearch.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
/*
* i就是actionId或者keyId,通过actionId判断点击的按钮是否是软键盘的搜索
* 这里有一个坑,应该算是sdk版本不同留下的坑
* 在sdk30开发中,i的变量名叫做actionId,
* 我非常确定,当点击搜索按钮时actionId和EditorInfo.IME_ACTION_SEARCH是相等的,
* 即action == EditorInfo.IME_ACTION_SEARCH == 3
* 但是在sdk26中i = 66,EditorInfo.IME_ACTION_SEARCH = 3
* 不过keyEvent.KEYCODE_ENTER = 66,所以我要他妈使用keyEvent.KEYCODE_ENTER?
* 原理是因为搜索按钮把回车按钮取代了吗????
* */
if (i == keyEvent.KEYCODE_ENTER){
// 执行的事件
Toast.makeText(getContext(),edit_newsSearch.getText().toString(),Toast.LENGTH_SHORT).show();
}
return false;
}
});

拓展:在EditText的父布局或者顶层布局中添加属性android:focusableInTouchMode=”true”和android:focusable=”true”,可以禁止EditText自动获取焦点