gpt4 book ai didi

android - 如何在 Android 中发送指针事件

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:03:29 25 4
gpt4 key购买 nike

我正在尝试检测 Android 中的虚拟键盘高度。

我发现了一个类似的主题:Get the height of virtual keyboard in Android

看来作者找到了检测高度的方法:

I found a way to get it. After I request to open virtual keyboard, I send pointer event that I generate. their y coordinate starts from height of device and decreases.

我不知道该怎么做。

最佳答案

我将使用您发布的链接中提供的代码:

// Declare Variables

int softkeyboard_height = 0;
boolean calculated_keyboard_height;
Instrumentation instrumentation;

// Initialize instrumentation sometime before starting the thread
instrumentation = new Instrumentation();

mainScreenView 是您的基本 View ,您的 Activity View 。 m(ACTION_DOWN) 和 m1(ACTION_UP) 是使用 Instrumentation#sendPointerSync(MotionEvent) 调度的触摸事件。逻辑是调度到显示键盘的位置的 MotionEvent 将导致以下 SecurityException:

java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission

因此,我们从屏幕底部开始,并在循环的每次迭代中向上(通过递减 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):

Dispatch a pointer event. Finished at some point after the recipient has returned from its event processing, though it may not have completely finished reacting from the event -- for example, if it needs to update its display as a result, it may still be in the process of doing that.

关于android - 如何在 Android 中发送指针事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8600299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com