2

我有一个ActionBar和一些菜单项设置为ActionBar像这样显示:

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

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

那可能吗?如何?谢谢。

4

1 回答 1

0

允许长按 MenuItem 并不是一个好方法。

使用 Java 反射已尝试使其成为可能:

 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

于 2013-10-14T17:23:55.853 回答