2017-09-14 175 views
0

在Android的基於Xamarin表單的應用程序中,我遇到Statusbar與ContentPage重疊的問題。XamarinForm:Android:狀態欄重疊內容頁面

設置硬代碼XAML中ContentPage的厚度值可能無法用於每個Android設備。

所以,我在博客上找到了一些解決方案,但沒有任何人工作。從Xamarin.Droid項目計算狀態欄高度並設置填充到內容頁面的地方。

因此,任何人都請通過計算Statusbar高度來建議如何在運行時的內容頁面上設置Padding頂部?

在此先感謝。

回答

0

我找到了解決方案:

爲此,我們需要創建自定義渲染器。

請在下面找到從Xamarin.Droid項目提到的代碼PageRenderer:

[assembly: ExportRenderer(typeof(ContentPage), typeof(MyContentPageRenderer))] 

命名空間ProjectName.Droid.Renderer

{

public class MyContentPageRenderer : PageRenderer 
{ 
    public MyContentPageRenderer() 
    { 
    } 


    protected override void OnElementChanged(ElementChangedEventArgs<Page> e) 
    { 
     base.OnElementChanged(e); 


    } 

    protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) 
    { 
     base.OnElementPropertyChanged(sender, e); 



     float pixWidth = (float)Resources.DisplayMetrics.WidthPixels; 
     float fdpWidth = (float)App.Current.MainPage.Width; 
     float pixPerDp = pixWidth/fdpWidth; 

     this.Element.Padding = new Thickness(0, MainActivity.StatusBarHeight/pixPerDp, 0, 0); 

    } } } 

並請找 「MainActivity」 的代碼如下面針對StatusBarHeight計算所述:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity 
{ 
    public static int StatusBarHeight; 

    protected override void OnCreate(Bundle bundle) 
    { 

     base.OnCreate(bundle); 

     global::Xamarin.Forms.Forms.Init(this, bundle); 

     if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) 
     { 
      Window.DecorView.SystemUiVisibility = 0; 
      var statusBarHeightInfo = typeof(FormsAppCompatActivity).GetField("_statusBarHeight", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); 
      statusBarHeightInfo.SetValue(this, 0); 
      Window.SetStatusBarColor(new Android.Graphics.Color(18, 52, 86, 255)); 
     } 

     LoadApplication(new App()); 

     StatusBarHeight = getStatusBarHeight(); 

    } 

    public int getStatusBarHeight() 
    { 

     int statusBarHeight = 0, totalHeight = 0, contentHeight = 0; 
     int resourceId = Resources.GetIdentifier("status_bar_height", "dimen", "android"); 
     if (resourceId > 0) 
     { 
      statusBarHeight = Resources.GetDimensionPixelSize(resourceId); 


     } 
     return statusBarHeight; 
    } 
} 

這解決了我的問題。