Search code examples
xamarin.formssizestatusbar

how can i get status bar height in xamarin.forms?


I am trying to get status / action bar height in my application. I got some of how we can get it in native android. can we get status / action bar height in xamarin.forms ?if yes then how? please help if anybody have idea about it. enter image description here


Solution

  • You can do this by creating your own dependency service. (https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/dependency-service/introduction/)

    In your shared code, create an interface for example IStatusBar:

    public interface IStatusBar
        {
            int GetHeight();
        }
    

    Add implementation for Android platform:

    [assembly: Dependency(typeof(StatusBar))]
    namespace StatusBarApp.Droid
    {
        class StatusBar : IStatusBar
        {
            public static Activity Activity { get; set; }
    
            public int GetHeight()
            {
                int statusBarHeight = -1;
                int resourceId = Activity.Resources.GetIdentifier("status_bar_height", "dimen", "android");
                if (resourceId > 0)
                {
                    statusBarHeight = Activity.Resources.GetDimensionPixelSize(resourceId);
                }
                return statusBarHeight;
            }
        }
    }
    

    Activity property is set from MainActivity.cs:

    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        {
            protected override void OnCreate(Bundle bundle)
            {
                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;
    
                base.OnCreate(bundle);
    
                global::Xamarin.Forms.Forms.Init(this, bundle);
    
                StatusBar.Activity = this;
    
                LoadApplication(new App());
            }
        }
    

    This is how you call the implementation from the shared code:

    int statusBarHeight = DependencyService.Get<IStatusBar>().GetHeight();
    

    Implementation for IOS platform:

    [assembly: Dependency(typeof(StatusBar))]
    namespace StatusBarApp.iOS
    {
        class StatusBar : IStatusBar
        {
            public int GetHeight()
            {
                return (int)UIApplication.SharedApplication.StatusBarFrame.Height;
            }
        }
    }