目的
在手机上进行聊天时,键盘弹起会盖住聊天窗口,所以需要键盘弹起的时候,将界面也进行上移。
解决
安卓
publicint GetKeyboardHeight()
{
using (var unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
var unityPlayer = unityClass.GetStatic<AndroidJavaObject>("currentActivity").Get<AndroidJavaObject>("mUnityPlayer");
var view = unityPlayer.Call<AndroidJavaObject>("getView");
var dialog = unityPlayer.Get<AndroidJavaObject>("b");
if (view == null || dialog == null)
return 0;
var decorHeight = 0;
if (true)//includeInput
{
var decorView = dialog.Call<AndroidJavaObject>("getWindow").Call<AndroidJavaObject>("getDecorView");
if (decorView != null)
decorHeight = decorView.Call<int>("getHeight");
}
using (var rect = new AndroidJavaObject("android.graphics.Rect"))
{
view.Call("getWindowVisibleDisplayFrame", rect);
return Display.main.systemHeight - rect.Call<int>("height") + decorHeight;
}
}
}
苹果
public int GetKeyboardHeight()
{
return (int)TouchScreenKeyboard.area.height * Display.main.systemHeight / Screen.height;
}
调用
float k = gameObject.GetComponentInParent<CanvasScaler>().GetComponent<RectTransform>().sizeDelta.y;
float keyboardHeight = SdkManager.Instance.GetKeyboardHeight();
float keyboardHeightUi = keyboardHeight * k / Display.main.systemHeight;
m_Rt.anchoredPosition = Vector3.up * keyboardHeightUi;