1.使软件盘显示搜索按钮
设置edittext属性:
android:imeOptions="actionSearch"
edittext当作搜索按钮的事件监听
<EditText
android:id="@+id/search_bar_et"
android:layout_width="match_parent"
android:layout_height="40dip"
android:imeOptions="flagNoExtractUi|actionSearch"
android:singleLine="true"/>
edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {}}}
知识点补充: Android软键盘输入imeOptions
根据输入框输入完成后要执行的业务逻辑指定软键盘右下角Action按钮的样式和行为,如让右下角按钮显示为“搜索”,点击后执行搜索。
imeOptions 值:
IME_ACTION_UNSPECIFIED. 编辑器决定Action按钮的行为
IME_ACTION_GO Action按钮将作为 “开始” 按钮。点击后跳转到输入字符的意图页面
IME_ACTION_SEARCH 执行“搜索”按钮。点击后跳转到输入字符的搜索结果页面
IME_ACTION_SEND. 执行 “发送”按钮。点击后将输入字符发送给它的目标
IME_ACTION_NEXT. Action按钮将作为next(下一个)按钮。点击后将进行下一个输入框的输入
IME_ACTION_DONE. Action按钮将作为done(完成)按钮。点击后IME输入法将会关闭
IME_ACTION_PREVIOUS. 作为”上一个”按钮。点击后将进行上一个输入框的输入
IME_FLAG_NO_FULLSCREEN. 请求IME输入法永远不要进入全屏模式
IME_FLAG_NAVIGATE_PREVIOUS. 类似IME_FLAG_NAVIGATE_NEXT, 表明这里有后退导航可以关注的兴趣点
IME_FLAG_NAVIGATE_NEXT. 表明这里有前进导航可以关注的兴趣点,类似IME_ACTION_NEXT,不过允许IME输入多行且提供前进导航。
IME_FLAG_NO_EXTRACT_UI. 请求IME输入法不要显示额外的文本UI
IME_FLAG_NO_ACCESSORY_ACTION. 和一个Action结合使用表明在全屏输入法中不作为可访问性按钮
IME_FLAG_NO_ENTER_ACTION. 多行文本将自动设置了该标志位,执行Action时为换行效果,如果未设置,IME输入法将把Enter按钮自动替换为Action按钮
IME_FLAG_FORCE_ASCII. 请求IME输入法接受ASCII字符的输入
2.软件盘的显示和隐藏
显示
public static boolean showKeyboard(final View windowView) {
if (windowView == null) {
return false;
}
if (!windowView.isFocused()) {
windowView.requestFocus();
}
Context context = windowView.getContext();
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.showSoftInput(windowView, InputMethodManager.SHOW_IMPLICIT);
}
隐藏
public static boolean hideKeyboard(View windowView) {
if (windowView == null) {
return false;
}
Context context = windowView.getContext();
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.hideSoftInputFromWindow(windowView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
不依赖焦点的隐藏键盘
public static void hideKeyboard(Context context) {
if (context == null) {
return;
}
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
}
}