在布局加载的过程中是无法弹出软键盘的,所以需要适当的延迟一下软键盘的弹出
//获取焦点
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
//延迟弹出软键盘
Timer timer = new Timer();
timer.schedule(new TimerTask(){
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) editText.getContext( ).getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText,InputMethodManager.SHOW_FORCED);
}
}, 300);
稍微封装一下弹出和隐藏
private void showKeyboard() {
ThreadUtils.postDelayedOnUiThread(() -> {
InputMethodManager imm = (InputMethodManager) etSearch.getContext().getSystemService(Service.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}, 0);
}
public void hideKeyBoard() {
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.toggleSoftInput(1, InputMethodManager.HIDE_NOT_ALWAYS);
/*隐藏软键盘*/
if (imm.isActive()) {
imm.hideSoftInputFromWindow(getApplicationWindowToken(), 0);
}
}
|