如何在 xamarin.forms 中获取状态栏高度? [英] how can i get status bar height in xamarin.forms?
问题描述
我正在尝试在我的应用程序中获取状态/操作栏高度.我得到了一些如何在原生 android 中获得它的方法.我们可以在 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.
推荐答案
您可以通过创建自己的依赖服务来实现这一点.(https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/dependency-service/introduction/)
You can do this by creating your own dependency service. (https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/dependency-service/introduction/)
在您的共享代码中,创建一个接口,例如 IStatusBar:
In your shared code, create an interface for example IStatusBar:
public interface IStatusBar
{
int GetHeight();
}
为 Android 平台添加实现:
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 属性是从 MainActivity.cs 设置的:
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();
IOS平台实现:
[assembly: Dependency(typeof(StatusBar))]
namespace StatusBarApp.iOS
{
class StatusBar : IStatusBar
{
public int GetHeight()
{
return (int)UIApplication.SharedApplication.StatusBarFrame.Height;
}
}
}
这篇关于如何在 xamarin.forms 中获取状态栏高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!