如何在Android上使用Unity显示触摸屏键盘时调整视图大小?

在Unity中,我无法控制触摸屏键盘。 TouchScreenKeyboard类只有一个Android参数。

if(TouchScreenKeyboard.visible) { float keyboardHeight = TouchScreenKeyboard.area.height; // will resize the view here! But this return zero! } 

有没有其他方法可以知道Android上键盘的高度?

这应该做的伎俩( 在这里找到 ):

  public int GetKeyboardSize() { using(AndroidJavaClass UnityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { AndroidJavaObject View = UnityClass.GetStatic("currentActivity").Get("mUnityPlayer").Call("getView"); using(AndroidJavaObject Rct = new AndroidJavaObject("android.graphics.Rect")) { View.Call("getWindowVisibleDisplayFrame", Rct); return Screen.height - Rct.Call("height"); } } } 

很久以前,但是为了防止任何人再次与它斗争,我设法使用这个MonoBehaviour类找到了一个带有InputField的面板的解决方案。 我将它附加到InputField并链接应该resize的面板。

 public class InputFieldForScreenKeyboardPanelAdjuster : MonoBehaviour { // Assign panel here in order to adjust its height when TouchScreenKeyboard is shown public GameObject panel; private InputField inputField; private RectTransform panelRectTrans; private Vector2 panelOffsetMinOriginal; private float panelHeightOriginal; private float currentKeyboardHeightRatio; public void Start() { inputField = transform.GetComponent(); panelRectTrans = panel.GetComponent(); panelOffsetMinOriginal = panelRectTrans.offsetMin; panelHeightOriginal = panelRectTrans.rect.height; } public void LateUpdate () { if (inputField.isFocused) { float newKeyboardHeightRatio = GetKeyboardHeightRatio(); if (currentKeyboardHeightRatio != newKeyboardHeightRatio) { Debug.Log("InputFieldForScreenKeyboardPanelAdjuster: Adjust to keyboard height ratio: " + newKeyboardHeightRatio); currentKeyboardHeightRatio = newKeyboardHeightRatio; panelRectTrans.offsetMin = new Vector2(panelOffsetMinOriginal.x, panelHeightOriginal * currentKeyboardHeightRatio); } } else if (currentKeyboardHeightRatio != 0f) { if (panelRectTrans.offsetMin != panelOffsetMinOriginal) { SmartCoroutine.DelayedExecute(this, () => { Debug.Log("InputFieldForScreenKeyboardPanelAdjuster: Revert to original"); panelRectTrans.offsetMin = panelOffsetMinOriginal; }, 0.5f); } currentKeyboardHeightRatio = 0f; } } private float GetKeyboardHeightRatio() { if (Application.isEditor) { return 0.4f; // fake TouchScreenKeyboard height ratio for debug in editor } #if UNITY_ANDROID using (AndroidJavaClass UnityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { AndroidJavaObject View = UnityClass.GetStatic("currentActivity").Get("mUnityPlayer").Call("getView"); using (AndroidJavaObject rect = new AndroidJavaObject("android.graphics.Rect")) { View.Call("getWindowVisibleDisplayFrame", rect); return (float)(Screen.height - rect.Call("height")) / Screen.height; } } #else return (float)TouchScreenKeyboard.area.height / Screen.height; #endif } }