我最近几天一直在使用libgdx开发一个Android项目。在开发过程中,遇到了一个问题:当软键盘弹出时,会覆盖一些视图,因此我想获取高度来解决这个问题。
我知道在使用Android API开发项目时可以设置软输入模式来解决这个问题,但是Libgdx有没有提供任何方式来解决呢?
我最近几天一直在使用libgdx开发一个Android项目。在开发过程中,遇到了一个问题:当软键盘弹出时,会覆盖一些视图,因此我想获取高度来解决这个问题。
我知道在使用Android API开发项目时可以设置软输入模式来解决这个问题,但是Libgdx有没有提供任何方式来解决呢?
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import com.badlogic.gdx.backends.android.AndroidApplication;
/**
* Container for platform-specific android implementation.
*/
public class PlatformSpecificAndroidImpl implements PlatformSpecificService {
private AndroidApplication androidApplication;
private AndroidGlobalLayoutListener globalLayoutListener;
public PlatformSpecificAndroidImpl(AndroidApplication androidApplication) {
this.androidApplication = androidApplication;
}
/**
* Initialize platform services. This method should be called from the gdx applications "create()" method.
*/
@Override
public void init() {
globalLayoutListener = new AndroidGlobalLayoutListener(androidApplication);
Window window = androidApplication.getWindow();
if (window != null) {
View decorView = window.getDecorView();
if (decorView != null) {
View rootView = decorView.getRootView();
if (rootView != null) {
ViewTreeObserver viewTreeObserver= rootView.getViewTreeObserver();
if (viewTreeObserver != null) {
viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener);
}
}
}
}
}
/**
* Get the window height that is really usable, subtracting the soft-keyboard if open.
* @return usable window height
*/
@Override
public int getUsableWindowHeight() {
if (globalLayoutListener != null) {
return globalLayoutListener.getHeight();
}
return 0;
}
private static class AndroidGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
private AndroidApplication androidApplication;
private int height;
private AndroidGlobalLayoutListener(AndroidApplication androidApplication) {
this.androidApplication = androidApplication;
}
@Override
public void onGlobalLayout() {
height = 0;
Window window = androidApplication.getWindow();
if (window != null) {
View currentFocus = window.getCurrentFocus();
if (currentFocus != null) {
View rootView = currentFocus.getRootView();
if (rootView != null) {
Rect rect = new Rect();
rootView.getWindowVisibleDisplayFrame(rect);
height = rect.bottom;
}
}
}
}
public int getHeight() {
return height;
}
}
}
是的,你可以通过Viewtree Observer和全局布局监听器的帮助来实现,只需尝试以下步骤:
现在,每当Android显示软键盘时,它将重新调整您的屏幕,并在监听器上接收调用。这就是您现在需要做的唯一事情,即计算重新调整大小后您的根视图与原始大小之间的差异。如果差异大于150,则认为已经展开了键盘。
以下是示例代码:
root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
public void onGlobalLayout(){
int heightDiff = root.getRootView().getHeight()- root.getHeight();
// IF height diff is more then 150, consider keyboard as visible.
}
});