Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Android PopupMenu width

I am having trouble changing the width of the Appcompat PopupMenu because the menu item uses this layout abc_popup_menu_item_layout.xml in MenuPopupHelper.java, which set menu item minWidth to 196dip.

<android.support.v7.internal.view.menu.ListMenuItemView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="?attr/dropdownListPreferredItemHeight"
        android:minWidth="196dip"
        android:paddingRight="16dip">

I tried to override minWidth as well as dropDownWidth in the following properties in my style.xml. I also tried to override minWidth in android:dropDownItemStyle, but it did not help. I start to wonder if it is possible to override this hard coded attribute of ListMenuItemView. Has anyone succeeded in modifying a PopupMenu width?

<style name="OrderDetailsActivity" parent="AppTheme">
    <item name="android:textAppearanceLargePopupMenu">@style/OrderDetailsPopupMenuTextAppearanceLarge</item>
    <item name="android:textAppearanceSmallPopupMenu">@style/OrderDetailsPopupMenuTextAppearanceSmall</item>
    <item name="android:dropDownListViewStyle">@style/OrderDetailsListDropDownStyle</item>
    <item name="dropDownListViewStyle">@style/OrderDetailsListDropDownStyle</item>
</style>

<style name="OrderDetailsPopupMenuTextAppearanceLarge" parent="@android:style/TextAppearance.DeviceDefault.Widget.PopupMenu.Large">
    <item name="android:fontFamily">sans-serif-medium</item>
    <item name="android:textSize">@dimen/font_size_medium</item>
</style>

<style name="OrderDetailsPopupMenuTextAppearanceSmall" parent="@android:style/TextAppearance.DeviceDefault.Widget.PopupMenu.Small">
    <item name="android:fontFamily">sans-serif-medium</item>
    <item name="android:textSize">@dimen/font_size_medium</item>
</style>

<style name="OrderDetailsListDropDownStyle" parent="Widget.AppCompat.ListView.DropDown">
    <item name="android:divider">@drawable/list_divider</item>
</style>
like image 431
YoYoMyo Avatar asked Nov 09 '22 17:11

YoYoMyo


1 Answers

You can prepare your custom popup menu item layout file and update this static field using reflection in onCreate() method of Your Application class:

private void updatePopUpMenuItemLayout() {
    try {
        Field field = MenuPopupHelper.class.getDeclaredField("ITEM_LAYOUT");
        field.setAccessible(true);
        field.set(null, R.layout.custom_popup_menu_item_layout);
    } catch (Exception e) {
        Log.e("TAG", e.getMessage());
    }
}
like image 177
mdabrowski89 Avatar answered Nov 14 '22 22:11

mdabrowski89