繁体   English   中英

Android actionbar菜单项长按检测可能吗?

[英]Android actionbar menu item long click detect possible?

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

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

onOptionsItemSelected(MenuItem item)在捕获正常点击时效果很好,但是我想长时间按住,所以我可以做一些与默认行为不同的操作。

那可能吗? 如何? 谢谢。

允许长时间按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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM