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.
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;
}
}
}
Common code (in App.xaml.cs)
public static int StatusBarHeight {get; set;}
Android part (in MainActivity.cs, in the OnCreate method)
int resourceId = Resources.GetIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0)
{
App.StatusBarHeight = (int)(Resources.GetDimensionPixelSize(resourceId) / Resources.DisplayMetrics.Density);
}
iOS part (in AppDelegate.cs, in the FinishedLaunching method)
App.StatusBarHeight = (int)UIApplication.SharedApplication.StatusBarFrame.Height;
So App.StatusBarHeight will be initialized when the App will be launched, then you will be able to use it anywhere in the common code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With