在android中监听键盘显示或隐藏事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24388492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Listen for keyboard show or hide event in android
提问by AlexanderNajafi
I am trying to listen for events that occurs when the keyboard is shown or hidden. Is this possible in Android? I am not trying to figure out if the keyboard is shown or hidden when I start my activity, I would like to listen for events.
我正在尝试侦听显示或隐藏键盘时发生的事件。这在Android中可能吗?当我开始我的活动时,我不想弄清楚键盘是显示还是隐藏,我想监听事件。
回答by duggu
Try below code:-
试试下面的代码:-
// from the link above
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks whether a hardware keyboard is available
if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
} else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
}
}
or
或者
boolean isOpened = false;
public void setListnerToRootView(){
final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
if (heightDiff > 100 ) { // 99% of the time the height diff will be due to a keyboard.
Toast.makeText(getApplicationContext(), "Gotcha!!! softKeyboardup", 0).show();
if(isOpened == false){
//Do two things, make the view top visible and the editText smaller
}
isOpened = true;
}else if(isOpened == true){
Toast.makeText(getApplicationContext(), "softkeyborad Down!!!", 0).show();
isOpened = false;
}
}
});
}
or
或者
for below code you have to extend LinearLayout.
对于下面的代码,您必须扩展 LinearLayout。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
final int actualHeight = getHeight();
if (actualHeight > proposedheight){
// Keyboard is shown
} else {
// Keyboard is hidden
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
see below link:-
见以下链接:-
How to capture the "virtual keyboard show/hide" event in Android?