1.windowSoftInputMode设置
windowSoftInputMode的参数分为两种
限定进入Activity时键盘的状态(弹出还是隐藏)
stateUnspecified:未指定的默认状态
stateUnchanged :不改变键盘的状态——与上一个界面的键盘状态相同
stateHidden :隐藏键盘
stateAlwaysHidden:隐藏键盘——进入下一个界面后返回还是隐藏键盘
stateVisible :显示键盘
stateAlwaysVisible:显示键盘——进入下一个界面后返回还是显示键盘
设置键盘弹出时页面布局的改变的状态
adjustUnspecified:未指定的默认状态,自动适配屏幕
adjustResize :Activity的主窗口总是会被调整大小,从而保证软键盘显示空间,键盘作为布局的一部分来展示
adjustPan :利用布局移动来保证输入框在视野范围内
2.动态显示/隐藏键盘
显示键盘
editText.setFocusableInTouchMode(true);
editText.requestFocus();
InputMethodManager inputManager =(InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(editText, 0);
隐藏键盘
InputMethodManager inputManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
3.键盘高度的监听
当系统提供的adjustResize和adjustPan 不能满足页面布局设计的需求时可以通过监听键盘高度来动态改变布局
final View decorView= getWindow().getDecorView();
decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect=new Rect();
decorView.getWindowVisibleDisplayFrame(rect);
int displayHeight=rect.bottom;
int height=decorView.getHeight();
int keyboardHeight=height-displayHeight;
Log.i("KEYBOARD","键盘的高度是"+keyboardHeight);
}
});
4.改变键盘回车键显示和功能
有时候需要改变键盘回车键来实现搜索、发送、完成等功能。
// et.setImeOptions(EditorInfo.IME_ACTION_DONE);//完成
// et.setImeOptions(EditorInfo.IME_ACTION_SEND);//发送
// et.setImeOptions(EditorInfo.IME_ACTION_SEARCH);//搜索
// et.setImeOptions(EditorInfo.IME_ACTION_GO);//前往
// et.setImeOptions(EditorInfo.IME_ACTION_NEXT);//下一项
// et.setImeOptions(EditorInfo.IME_ACTION_NONE);//默认
// et.setImeOptions(EditorInfo.IME_ACTION_PREVIOUS);//上一项
et.setImeOptions(EditorInfo.IME_ACTION_UNSPECIFIED);//未指明
et.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if(i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_UP){
Toast.makeText(MainActivity.this, "按下了回车键", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
}
最后,改变键盘回车键必须是singleLine的EditText才能实现