Home » Android » android – PopupMenu equivalent in ActionBarSherlock

android – PopupMenu equivalent in ActionBarSherlock

Posted by: admin June 15, 2020 Leave a comment

Questions:

What is the PopupMenu equivalent in ActionBarSherlock? I can’t seem to find it. Its API 11, why is it absent?

How to&Answers:

The Class MenuPopupHelper pretty much does the job. I didn’t find an easy way to listen for Item Clicks though, so I implemented this class that derives from MenuPopupHelper:

public class MenuPopup extends MenuPopupHelper {

    OnMenuItemClickListener onMenuItemClickListener;

    public MenuPopup(Context context, MenuBuilder menu, View anchorView) {
        super(context, menu, anchorView);
    }

    public void setOnMenuItemClickListener(
            OnMenuItemClickListener onMenuItemClickListener) {
        this.onMenuItemClickListener = onMenuItemClickListener;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        super.onItemClick(parent, view, position, id);
        if (onMenuItemClickListener != null)
            onMenuItemClickListener.onMenuItemClick(position);
    }

    public interface OnMenuItemClickListener{
        public void onMenuItemClick(int itemID);
    }
}

Answer:

Added PopupMenu in ActionBarSherlock.

Styling of the PopupMenu

<item name="popupMenuStyle">@style/PopupMenu.MyAppTheme</item>      

<style name="PopupMenu.MyAppTheme" parent="@style/Widget.Sherlock.ListPopupWindow">
    <item name="android:popupBackground">@android:color/white</item>
</style>

Answer:

I’m working on this currently. I did what was suggested by CommonsWare about backporting it. I basically took the PopupMenu.java source code and replaced the package imports with the actionbarsherlock equivalents. It seems to work fine on the gingerbread and ics devices I tested on. The catch though is in actionbarsherlocks MenuPopupHelper class I had to comment lines referencing View_HasStateListenerSupport like:

((View_HasStateListenerSupport)anchor).addOnAttachStateChangeListener(this);

for some reason. If I didn’t I would get a ClassCastException:

E/AndroidRuntime(9197): FATAL EXCEPTION: main
E/AndroidRuntime(9197): java.lang.ClassCastException: android.widget.Button cannot be cast to com.actionbarsherlock.internal.view.View_HasStateListenerSupport
E/AndroidRuntime(9197): at com.actionbarsherlock.internal.view.menu.MenuPopupHelper.tryShow(MenuPopupHelper.java:121)
E/AndroidRuntime(9197): at com.actionbarsherlock.internal.view.menu.MenuPopupHelper.show(MenuPopupHelper.java:102)

I’m unsure if commenting out that listener could cause problems for other classes that utilize MenuPopupHelper or why they are causing this exception (maybe a bug). But I thought I would share what I tried, so it may help anyone looking into this.