2013-08-26 114 views
5

我知道我可以使用「android:windowSoftInputMode =」adjustPan「來做一些自動偏移操作,但我真的想爲某些特殊目的獲得軟件鍵盤高度如何獲得Android軟鍵盤高度?

我發現這裏有一個類似的話題: Getting the dimensions of the soft keyboard。但很顯然,這不是一個通用的解決方案。

有沒有一種常見的方法或內置方法來獲得軟鍵盤高度?(或者我怎樣才能獲得當前光標位置和軟件鍵盤頂部位置之間的偏移值? )

非常感謝

+0

兩旺你好,您的問題解決了嗎?我也需要相同的。 – jrhamza

+0

沒有獲取鍵盤高度的內置方法。你必須使用ViewTreeObserver.OnGlobalLayoutListener() – aravindkanna

回答

0

在這裏我的解決方案,它也hacky,但解決問題。

  1. 我在屏幕底部有透明背景的臨時視圖。
  2. 我在@bill建議的清單中的活動標記中添加了android:windowSoftInputMode="adjustResize"標誌。
  3. 現在的主要故事在onGlobalLayout()。在那裏,我計算溫度鑑於y axisroot view

    final View view = findViewById(R.id.base); 
    view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    
    @Override 
    public void onGlobalLayout() { 
    
        int rootViewHeight = view.getRootView().getHeight(); 
        View tv = findViewById(R.id.temp_view); 
        int location[] = new int[2]; 
        tv.getLocationOnScreen(location); 
        int height = (int) (location[1] + tv.getMeasuredHeight()); 
        deff = rootViewHeight - height; 
        // deff is the height of soft keyboard 
    } 
    }); 
    
0

高度之間的差異獲取Xamarin.Android軟鍵盤高度,使用ViewTreeObserver.IOnGlobalLayoutListener偵聽GlobalLayout更改事件並計算改變差值爲了獲得鍵盤的高度,前後查看根視圖。您可以在原生Android代碼中執行類似操作。

這裏是代碼:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity 
{ 
     public static Android.Views.View RootView = null; 
     public void DetectSoftKeyboardHeight() 
     { 
      RootView = this.FindViewById(Android.Resource.Id.Content); 
      if(RootView!=null) 
       RootView.ViewTreeObserver.AddOnGlobalLayoutListener(new MyLayoutListener()); 
     } 
} 
/// <summary> 
/// My layout listener. 
/// Detect Android Soft keyboard height 
/// </summary> 
public class MyLayoutListener : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener 
{ 
    public void OnGlobalLayout() 
    { 
     // do stuff here 
     Android.Graphics.Rect r = new Android.Graphics.Rect(); 
     if (Mobibranch.Droid.MainActivity.RootView != null) 
     { 
      Mobibranch.Droid.MainActivity.RootView.GetWindowVisibleDisplayFrame(r); 

      int screenHeight = Mobibranch.Droid.MainActivity.RootView.RootView.Height; 
      int keyboardHeight = screenHeight - (r.Bottom); 

      if (keyboardHeight > 0) 
      { 
       //Keyboard is up on screen 
       Android.Util.Log.Verbose("[[[[MyLayoutListener]]]]", "Keyboard is up on screen, Height: "+keyboardHeight); 
      } 
      else 
      { 
       //Keyboard is hidden 
      } 
     } 
    } 
}