Android操作栏菜单项长按检测可能吗?

时间:2013-01-13 04:13:57

标签: android callback android-actionbar menuitem

我有一个ActionBar和一些设置为ActionBar的菜单项,如下所示:

<item
        android:id="@+id/menu_play1"
        android:orderInCategory="100"
        android:showAsAction="ifRoom|withText" 
        android:title="Play1x"/>

onOptionsItemSelected(MenuItem item)可以很好地捕捉到正常的点击次数,但我想长时间按下,这样我就可以做一些与普通按下默认行为不同的事情。

这可能吗?如何?感谢。

1 个答案:

答案 0 :(得分:0)

允许长按MenuItems是不好的方法。

使用Java Reflection尝试使其成为可能:

 private interface OnMenuItemLongClickListener{
        boolean onMenuItemLongClik(MenuItem m);
    }
    private void getMenuItemsView(Activity a, final Menu m, final OnMenuItemLongClickListener listener) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException{
        View homeButton = a.findViewById(android.R.id.home);
        ViewParent parentOfHome = homeButton.getParent().getParent(); //ActionBarView is parent of home ImageView, see layout file in sources

        if (!parentOfHome.getClass().getName().contains("ActionBarView")) {
            parentOfHome = parentOfHome.getParent(); 
            Class absAbv = parentOfHome.getClass().getSuperclass(); //ActionBarView -> AbsActionBarView class
            Field actionMenuPresenterField = absAbv.getDeclaredField("mActionMenuPresenter");
            actionMenuPresenterField.setAccessible(true);
            Object actionMenuPresenter = actionMenuPresenterField.get(parentOfHome);
            Field actionMenuViewField = actionMenuPresenter.getClass().getSuperclass().getDeclaredField("mMenuView");
            actionMenuViewField.setAccessible(true);
            Object actionMenuView = actionMenuViewField.get(actionMenuPresenter);
            Field childrenField= actionMenuView.getClass().getSuperclass().getSuperclass().getDeclaredField("mChildren");
            childrenField.setAccessible(true);
            Field menuField =actionMenuPresenter.getClass().getSuperclass().getDeclaredField("mMenu");
            menuField.setAccessible(true);
            Object menu = menuField.get(actionMenuPresenter);
            Object[] menuItemsAsViews = (Object[])childrenField.get(actionMenuView);
            View.OnLongClickListener longListener = new View.OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {

                    return listener.onMenuItemLongClik(m.findItem(v.getId()));
                }
            };
            for(Object menuView:menuItemsAsViews ){
                View v = (View)menuView;
                v.setOnLongClickListener(longListener);
            }


    }
 }

你可以在这个要点上得到这个:https://gist.github.com/NikolaDespotoski/6978883