簡體   English   中英

獲取導航/操作欄的高度

[英]Get navigation/action bar height

我有一個Xamarin Forms項目,該項目使用Android的自定義工具欄。 工具欄在axml中定義為Layout,我將工具欄的minHeight設置為標准操作欄的高度。

對於我的應用程序中的特定頁面,我有一個自定義頁面渲染器,在其中我需要頂部(導航/操作)欄的高度。

我已經嘗試使用FindViewByID來獲取高度,並使用TypedValue來獲取高度,但這只給了我0。

我還能嘗試什么來獲得頁面渲染器中條形的高度?

App.cs(通用代碼)

public static int ActionBarHeight;

MainActivity,在OnCreate方法(Droid部分)中:

Android.Content.Res.TypedArray styledAttributes = Theme.ObtainStyledAttributes(new int[] { Android.Resource.Attribute.ActionBarSize });
App.ActionBarHeight = (int)(styledAttributes.GetDimension(0, 0) / Resources.DisplayMetrics.Density);
styledAttributes.Recycle();

如果要以像素為單位的高度:

App.ActionBarHeight = (int)styledAttributes.GetDimension(0, 0);

在Xamarin Android中,只有在OnMeasure方法之后,才能獲取視圖的寬度和高度。 OnMeasure之后將調用OnLayout方法。 這樣就可以在OnLayout方法中獲得寬度和高度。

class MyRender: PageRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
    {
        base.OnElementChanged(e);
    }

    protected override void OnLayout(bool changed, int l, int t, int r, int b)
    {
        System.Diagnostics.Debug.Write("OnLayout start");
        base.OnLayout(changed, l, t, r, b);
        for (int i = 0; i < ChildCount; i++)
        {
            Android.Views.View view = GetChildAt(i);
            int height = view.Height;
            int width = view.Width;
            System.Diagnostics.Debug.Write("height=" + height );
            System.Diagnostics.Debug.Write("width=" + width );
        }
        System.Diagnostics.Debug.Write("OnLayout end");

    }

}

在獲取width和height之前,必須確保已調用OnMeasure ,否則將始終為0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM