使用CustomRenderer获取Xamarin Forms中ContentPage的高度

问题描述

我想使用Customrenderer尝试导航栏的高度,但无论是Android平板电脑还是平板电脑,总是得到相同的值。

我正在使用以下代码

namespace OfflineFieldService.Droid
{
    public class CustomAndroidPageRenderer : PageRenderer
    {
        public CustomAndroidPageRenderer(Context context) : base(context)
        {

        }

        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged(e);
            var height = 0;
            var resources = Context.Resources;
            int resourceId = resources.GetIdentifier("navigation_bar_height","dimen","android");
            if (resourceId > 0)
            {
                height = resources.GetDimensionPixelSize(resourceId);
            }
            var scale = Resources.displayMetrics.Density;
            var heightinUnits = (height - .5) / scale;
            App.screenHeight = heightinUnits;

        }
    }```

[Attached image in the link,since dont have permission to embed][1]


  [1]: https://i.stack.imgur.com/UosCb.png

In the image whatever marked in yellow,need to get the height of it. I am using Shell template.

解决方法

导航栏高度iOS

public class NavRendererForiOS : NavigationRenderer
{
    protected override void OnElementChanged(VisualElementChangedEventArgs e)
    {
        base.OnElementChanged(e);

        var height = NavigationBar.Bounds.Height;
    }
}

导航栏高度android

public class NavRendererForAndroid : NavigationPageRenderer
{
    public CustomNaviForAndroid(Context context) : base(context)
    {

    }

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

        var height = 0;

        Resources resources = Context.Resources;
        int resourceId = resources.GetIdentifier("navigation_bar_height","dimen","android");
        if (resourceId > 0)
        {
            height = resources.GetDimensionPixelSize(resourceId);
        }
    }
}

Android屏幕尺寸

App.ScreenHeight = (int) (Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density);
App.ScreenWidth = (int) (Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density);

iOS屏幕尺寸

App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height;
App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...