Xamarin.Forms Android PopupMenu问题二

Xamarin.Forms Android PopupMenu问题二

在上一篇文章Xamarin.Android 使用PopupMenu遇到的问题文章中讲到了兼容Android 5.0及以下版本,但又带了一个新的问题。这个问题在所有Android版本App都会遇到,此时会抛出一个异常:

1Java.Lang.RuntimeException: Failed to resolve attribute at index 6

经过多番尝试(在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