Android系统并没有提供明显的API来监听软键盘的弹出和关闭,但是在某些情况下我们还是有办法来检测软键盘的弹出和关闭。
从StackOverflow找到了一个不错的方法。但是这种只适用于在manifest中目标Activity设置android:windowSoftInputMode=”adjustResize”的情况。
adjustResize表示The activity’s main window is always resized to make room for the soft keyboard on screen.
然后我们需要设置Activity的根视图的id,用来判断对话框弹出关闭使用。
布局的示例代码:
判断对话框出现或者关闭的逻辑代码如下:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final View activityRootView = findViewById(R.id.root_layout); activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { private int preHeight = 0; @Override public void onGlobalLayout() { int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight(); System.out.println("height differ = " + heightDiff); //在数据相同时,减少发送重复消息。因为实际上在输入法出现时会多次调用这个onGlobalLayout方法。 if (preHeight == heightDiff) { return; } preHeight = heightDiff; if (heightDiff > 100 ) {// System.out.println("input method shown!"); Toast.makeText(getApplicationContext(), "keyboard is shown", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "keyboard is hidden ", Toast.LENGTH_SHORT).show(); } } }); }
give your activity’s root view a known ID, say ‘@+id/activityRoot’, hook a GlobalLayoutListener into the ViewTreeObserver,
and from there calculate the size diff between your activity’s view root and the window size给你的Activity的根视图设置一个id,比如说”@+id/activityRoot”,在ViewTreeObserver上设置一个GlobalLayoutListener。然后计算你的Activity的根视图和Window尺寸的差值
如果插值大于 100 (这是一个相对比较合理的值),就认为是对话框弹出,否则为对话框隐藏。相关链接:http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android