How to force use of overflow menu on devices with menu button

前端 未结 11 547
谎友^
谎友^ 2020-11-22 14:04

I\'d like to have all of the menu items that don\'t fit into the ActionBar go into the overflow menu (the one that is reached from the Action Bar not the menu button) ev

11条回答
  •  无人及你
    2020-11-22 14:20

    This kind of method is prevented by the Android Developers Design System, but I found a way to pass it:

    Add this to your XML menu file:

    
    

    Next, create a class named 'AppPickActionProvider', and copy the following code to it:

        package com.example;
    
    import android.content.Context;
    import android.util.Log;
    import android.view.ActionProvider;
    import android.view.MenuItem;
    import android.view.MenuItem.OnMenuItemClickListener;
    import android.view.SubMenu;
    import android.view.View;
    
    public class AppPickActionProvider extends ActionProvider implements
            OnMenuItemClickListener {
    
        static final int LIST_LENGTH = 3;
    
        Context mContext;
    
        public AppPickActionProvider(Context context) {
            super(context);
            mContext = context;
        }
    
        @Override
        public View onCreateActionView() {
            Log.d(this.getClass().getSimpleName(), "onCreateActionView");
    
            return null;
        }
    
        @Override
        public boolean onPerformDefaultAction() {
            Log.d(this.getClass().getSimpleName(), "onPerformDefaultAction");
    
            return super.onPerformDefaultAction();
        }
    
        @Override
        public boolean hasSubMenu() {
            Log.d(this.getClass().getSimpleName(), "hasSubMenu");
    
            return true;
        }
    
        @Override
        public void onPrepareSubMenu(SubMenu subMenu) {
            Log.d(this.getClass().getSimpleName(), "onPrepareSubMenu");
    
            subMenu.clear();
    
            subMenu.add(0, 1, 1, "Item1")
            .setIcon(R.drawable.ic_action_home).setOnMenuItemClickListener(this);
    
            subMenu.add(0, 2, 1, "Item2")
                .setIcon(R.drawable.ic_action_downloads).setOnMenuItemClickListener(this);
        }
    
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch(item.getItemId())
            {
                case 1:
    
                    // What will happen when the user presses the first menu item ( 'Item1' )
    
                    break;
                case 2:
    
                    // What will happen when the user presses the second menu item ( 'Item2' )
    
                    break;
    
            }
    
            return true;
        }
    }
    

提交回复
热议问题