天天看點

Xamarin.Forms Android PopupMenu問題二Xamarin.Forms Android PopupMenu問題二

Xamarin.Forms Android PopupMenu問題二

在上一篇文章Xamarin.Android 使用PopupMenu遇到的問題文章中講到了相容Android 5.0及以下版本,但又帶了一個新的問題。這個問題在所有Android版本App都會遇到,此時會抛出一個異常:

經過多番嘗試(在Xamarin.Android中調試,原生Android中調試)依然沒能複現這個問題,是以我認為這個問題是Xamarin.Forms的一個bug。在微軟支援York的幫助下,找到了一個Workaround,非常感謝York。

先來分析這個問題:

問題出在ListMenuItemView(源碼),先看代碼:

public ListMenuItemView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs);
        mContext = context;

        TypedArray a =
                context.obtainStyledAttributes(
                        attrs, R.styleable.MenuView, defStyle, 0);

        mBackground = a.getDrawable(R.styleable.MenuView_android_itemBackground);
        mTextAppearance = a.getResourceId(R.styleable.
                MenuView_android_itemTextAppearance, -1);
        mPreserveIconSpacing = a.getBoolean(
                R.styleable.MenuView_android_preserveIconSpacing, false);
        mTextAppearanceContext = context;

        a.recycle();
    }      

ListMenuItemView在建立的時候,會去讀取一個style:R.styleable.MenuView,由于無法找到這個style是以抛出了該異常。

在這個Workaround中,我們在建立PopupMenu的時候給它設定一個Style就能解決這個問題了。

Workaround:

  1. 首先在Styles.xml中建立一個MenuStyle
    <style name ="MyPopupMenu" parent="MainTheme">
            <item name="android:popupBackground">#0F213F</item>
            <item name="android:disabledAlpha">0.5</item>
        </style>      
  2. 然後在将建立的Style應用到PopupMenu
    Context wrapper = new  Android.Support.V7.View.ContextThemeWrapper(context, Resource.Style.MyPopupMenu);
    PopupMenu popupMenu = new PopupMenu(wrapper, Control);      

這樣就能解決這個問題拉。

為什麼一開始沒又發現這個issue?

在解決相容Android5.0的問題時,最開始使用Android.Widget.PopupMenu進行調試。在并沒有清理代碼的情況下,将PopupMenu換為Android.Support.V7.Widget.PopupMenu,然後直接編譯運作成功了(此時若清理項目重新編譯,該問題就會出現,是以我認為是Xamarin.Forms的一個Bug)。直到後來Xamarin.Forms.InputKit釋出後,才發現該問題。

Android.Support.V7.Widget.PopupMenu源碼

MenuPopupHelper源碼

ListMenuItemView源碼

轉載于:https://www.cnblogs.com/devin_zhou/p/9782557.html