我正试图在Android中检测虚拟键盘高度。
我发现了类似的主题:Get the height of virtual keyboard in Android
作者似乎找到了一种检测高度的方法:
我找到了获得它的方法。在我请求打开虚拟键盘之后,我 发送我生成的指针事件。他们的y坐标从 装置高度和减少。
我不明白该怎么做。
答案 0 :(得分:3)
我将使用您发布的链接中提供的代码:
// Declare Variables
int softkeyboard_height = 0;
boolean calculated_keyboard_height;
Instrumentation instrumentation;
// Initialize instrumentation sometime before starting the thread
instrumentation = new Instrumentation();
mainScreenView
是您的基本视图,即您的活动视图。 m
(ACTION_DOWN)和m1
(ACTION_UP)是使用Instrumentation#sendPointerSync(MotionEvent)
分派的触摸事件。逻辑是调度到键盘显示位置的MotionEvent将导致以下SecurityException
:
java.lang.SecurityException:注入另一个应用程序需要 INJECT_EVENTS权限
因此,我们从屏幕底部开始,并在循环的每次迭代中逐步增加(通过递减y
)。对于一定数量的迭代,我们将得到一个SecurityException(我们将捕获):这意味着MotionEvent正在键盘上发生。当y
变得足够小(当它刚好在键盘上方)时,我们将突破循环并使用以下方法计算键盘的高度:
softkeyboard_height = mainScreenView.getHeight() - y;
代码:
Thread t = new Thread(){
public void run() {
int y = mainScreenView.getHeight()-2;
int x = 10;
int counter = 0;
int height = y;
while (true){
final MotionEvent m = MotionEvent.obtain(
SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_DOWN,
x,
y,
1);
final MotionEvent m1 = MotionEvent.obtain(
SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_UP,
x,
y,
1);
boolean pointer_on_softkeyboard = false;
try {
instrumentation.sendPointerSync(m);
instrumentation.sendPointerSync(m1);
} catch (SecurityException e) {
pointer_on_softkeyboard = true;
}
if (!pointer_on_softkeyboard){
if (y == height){
if (counter++ < 100){
Thread.yield();
continue;
}
} else if (y > 0){
softkeyboard_height = mainScreenView.getHeight() - y;
Log.i("", "Soft Keyboard's height is: " + softkeyboard_height);
}
break;
}
y--;
}
if (softkeyboard_height > 0 ){
// it is calculated and saved in softkeyboard_height
} else {
calculated_keyboard_height = false;
}
}
};
t.start();
Instrumentation#sendPointerSync(MotionEvent)
:
发送指针事件。在收件人之后的某个时刻完成 已从事件处理中返回,但可能没有 完全从事件中做出反应 - 例如,如果它 因此需要更新其显示,它可能仍然在 这样做的过程。
答案 1 :(得分:1)
使用OnGlobalLayoutListener,它对我来说非常适合。