希望有人会觉得这个答案有帮助:
有一个测试可以检测软键盘的确切高度,这涉及到 Launcher Activity 在屏幕调整大小事件发生时向游戏发送屏幕尺寸。
首先,在你的 LauncherActivity 的 rootView 的 ViewTreeObserver 上设置一个布局监听器:
public class AndroidLauncher extends AndroidApplication {
//...
public void setListenerToRootView() {
final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);
}
private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect visibleDisplayFrame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(visibleDisplayFrame);
game.screenResize(visibleDisplayFrame.width(), visibleDisplayFrame.height());
}
};
//...
}
如果您尝试获取根视图的高度,它将无法正常工作,因为大多数游戏都是全屏的。
不要忘记在适当的情况下添加和删除监听器:
@Override
protected void onCreate (Bundle savedInstanceState) {
//...
setListenerToRootView();
}
@Override
protected void onDestroy () {
super.onDestroy();
removeListenerToRootView();
}
public void removeListenerToRootView() {
final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content);
activityRootView.getViewTreeObserver().removeOnGlobalLayoutListener(keyboardLayoutListener);
}
接下来,在 Game Class 中声明 screenResize 方法,它将接收尺寸并将其发送到当前屏幕:
public class YourGame extends Game {
//...
public ScreenBase currentScreen;
//...
public void screenResize(float width, float height) {
if(currentScreen != null)
currentScreen.onScreenResize(width, height);
}
//...
}
每个涉及更改的屏幕都必须实现 onScreenResize 方法。引入具有抽象方法 onScreenResize 的屏幕抽象基类。 currentScreen 变量必须在构造函数中设置:
public abstract class ScreenBase implements Screen {
//...
public ScreenBase(YourGame game) {
//...
this.game = game;
this.game.currentScreen = this;
//....
}
public abstract void onScreenResize(float width, float height);
在您想要的任何屏幕中实现这些:
public class LoginScreen extends ScreenBase {
//...
@Override
public void onScreenResize(final float width, final float height) {
if(Gdx.graphics.getHeight() > height) {
Gdx.app.log("LoginScreen", "Height of keyboard: " + (Gdx.graphics.getHeight() - height));
}
}
}