Android Menu 汇总

作者:Otway
版权:转载请注明出处!

选项菜单 OptionMenu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@[+][package:]id/resource_name"
          android:title="string"
          android:titleCondensed="string"
          android:icon="@[package:]drawable/drawable_resource_name"
          android:onClick="method name"
          android:showAsAction=["ifRoom" | "never" | "withText" | "always" | "collapseActionView"]
          android:actionLayout="@[package:]layout/layout_resource_name"
          android:actionViewClass="class name"
          android:actionProviderClass="class name"
          android:alphabeticShortcut="string"
          android:alphabeticModifiers=["META" | "CTRL" | "ALT" | "SHIFT" | "SYM" | "FUNCTION"]
          android:numericShortcut="string"
          android:numericModifiers=["META" | "CTRL" | "ALT" | "SHIFT" | "SYM" | "FUNCTION"]
          android:checkable=["true" | "false"]
          android:visible=["true" | "false"]
          android:enabled=["true" | "false"]
          android:menuCategory=["container" | "system" | "secondary" | "alternative"]
          android:orderInCategory="integer" />
    <group android:id="@[+][package:]id/resource name"
           android:checkableBehavior=["none" | "all" | "single"]
           android:visible=["true" | "false"]
           android:enabled=["true" | "false"]
           android:menuCategory=["container" | "system" | "secondary" | "alternative"]
           android:orderInCategory="integer" >
        <item />
    </group>
    <item >
        <menu>
          <item />
        </menu>
    </item>
</menu>
  • android:showAsAction

    • ifRoom: Only place this item in the app bar if there is room for it
    • never: overflow menu
    • withText: only text android:title
    • always: on the bar
    • collapseActionView: android:actionLayout or android:actionViewClass
  • android:actionViewClass

      <item android:id="@+id/action_search"
             android:title="@string/action_search"
             android:icon="@drawable/ic_search"
             app:showAsAction="ifRoom|collapseActionView"
             app:actionViewClass="android.support.v7.widget.SearchView" />
    

    通过 setOnActionExpandListener() 监听展开收缩事件

  • android:actionViewLayout
    引入布局用于操作窗口,效果类似于android:actionViewClass

  • android:actionProviderClass

    <item android:id="@+id/action_share"
          android:title="share"
          app:showAsAction="always"
          app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
        />
    

    显示布局及可以监听相关事件

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem shareItem = menu.findItem(R.id.action_share);
        if (searchItem != null) {
            mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
            if (!setShareIntent()){
                menu.removeItem(R.id.action_share);
                //没有第三方可以分享,可以自定义
                //如果一个应用程序需要接受Share Intent发送的共享数据,
                // 那么需要在该应用程序的Manifest.xml文件中定义<intent-filter/>元素 
                 //android.intent.action.SEND,
                // 指明应用组件想要接受的intent
            }
        }
        return super.onCreateOptionsMenu(menu);
     }
    
    // Call to update the share intent
    private boolean setShareIntent() {
        if (mShareActionProvider != null) {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, "share content");//EXTRA_STREAM
    
            PackageManager pm = getPackageManager();
            //检查手机上是否存在可以处理这个动作的应用
            List<ResolveInfo> infoList = pm.queryIntentActivities(shareIntent, 0);
            if (!infoList.isEmpty()) {
                mShareActionProvider.setShareIntent(shareIntent);
                return true;
            }
            return false;
        }
        return false;
    }
    

    这种会记录偏好,可通过setShareHistoryFileName()设置记录的xml文件名

    设置setOnShareTargetSelectedListener监听条目点击事件

    可继承support包下ActionProvider自定义实现
    android.support.design.R.dimen.abc_action_bar_default_height_material

关于overflow menu在高版本不显示icon

安卓4.0之前会显示icon,高版本中不会显示,可以通过反射去设置icon的显示

    private void setIconEnable(Menu menu, boolean enable) {
        if (menu != null) {
            try {
                Class clazz = menu.getClass();
                if (clazz.getSimpleName().equals("MenuBuilder")) {
                    Method m = clazz.getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    //MenuBuilder实现Menu接口,创建菜单时,传进来的menu其实就是MenuBuilder对象                
                    m.invoke(menu, enable);
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }
    /**
     *  android 4.0以后使用AppCompatActivity必须在该方法中调用setIconEnable(),
     *  隐藏的menuitem的icon才会显示
     *  android 4.0以后其他的activity可以再onPrepreOptionMenu()中调用
     *  android 4.0以前可以正常显示overflow中的menuitem的icon
     * @param view
     * @param menu
     * @return
     */
    @Override
    protected boolean onPrepareOptionsPanel(View view, Menu menu) {
        setIconEnable(menu, true);//让在overflow中的menuitem的icon显示
        return super.onPrepareOptionsPanel(view, menu);
    }

手机实体菜单按键导致actionbar上的三个点图标不显示

    /**
     * 通过反射,设置实体menu键可用与否
     * 该方法在onCreate()中调用
     * @param enable  false:实体键不可用,会在actionbar上显示小点 
     *                true:可用,点击menu实体键才会显示menuitem
     */
    public void setHasPermanentMenuKey(boolean enable){
        try {
            ViewConfiguration mconfig = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if(menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(mconfig, enable);
            }
        } catch (Exception ex) {
        }
    }

可以通过自定义toolbar中布局实现理想效果

    ActionBar actionBar = getSupportActionBar();
    //设置自定义actionbar的view
    actionBar.setCustomView(R.layout.action_bar_layout);
    //设置展示的options为DISPLAY_SHOW_CUSTOM
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    //设置showCustom为true
    actionBar.setDisplayShowCustomEnabled(true);
    

上下文菜单 ContextMenu

浮动上下文菜单

  • registerForContextMenu(View view)注册于上下文菜单关联的View

  • ActivityFragment实现 registerForContextMenu(),当关联的View收到长按事件之后,会响应该方法。

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
    }
    
    
  • 事件监听

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
              //TODO
            default:
                return super.onContextItemSelected(item);
        }
    }
    
    

为单个视图启用上下文操作模式

  • 实现 ActionMode.Callback 接口。在其回调方法中,您既可以为上下文操作栏指定操作,又可以响应操作项目的点击事件,还可以处理操作模式的其他生命周期事件
  • 当需要显示操作栏时,调用activitystartActionMode()方法

弹出菜单 PopupMenu

    public void showPopup(View v) {
        PopupMenu popup = new PopupMenu(this, v);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.actions, popup.getMenu());
        popup.show();
    }

通过setOnMenuItemclickListener()设置监听

基于 Intent 的菜单项

通过intent_filter定义删选规则 CATEGORY_ALTERNATIVECATEGORY_SELECTED_ALTERNATIVE

调用Menu.addIntentOptions()来添加应用列表

ListPopupMenu

    final ListPopupWindow popup = new ListPopupWindow(mContext);
    List<String> list = new ArrayList<>();
    list.add("不喜欢");
    list.add("举报");
    popup.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
    popup.setAdapter(new ArrayAdapter<>(mContext, R.layout.biz_elevator_layout_note_popup_item, list));
    popup.setWidth( mContext.getResources().getDimensionPixelSize(R.dimen.width40));
    popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    popup.setAnchorView(mUserLayout);
    popup.setModal(true);
    popup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> parent, View view,
                         int position, long id) {
          switch (position) {
             case 0:
                break;
             case 1:
                break;
          }
          popup.dismiss();
       }
    });
    popup.setHorizontalOffset(-40);
    popup.setDropDownGravity(Gravity.END);
    popup.show();

PopupWindow

    final PopupWindow popupWindow = new PopupWindow(mContext);
    View inflate = LayoutInflater.from(mContext).inflate(R.layout.biz_elevator_layout_note_item_popup, null);
    View tvDislike = inflate.findViewById(R.id.popup_dislike);
    View tvReport = inflate.findViewById(R.id.popup_report);
    
    tvDislike.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
          if (mCallback != null) {
             mCallback.onDisLikeClicked(v, mPosition);
          }
          popupWindow.dismiss();
       }
    });
    tvReport.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
          if (mCallback != null) {
             mCallback.onReportClicked(v, mPosition);
          }
          popupWindow.dismiss();
       }
    });
    
    popupWindow.setContentView(inflate);
    popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
    // this setting can intercept the touch event when popupWindow opened
    popupWindow.setFocusable(true);
    popupWindow.setTouchable(true);
    popupWindow.setOutsideTouchable(true);
    PopupWindowCompat.showAsDropDown(popupWindow, v, -50, 10, Gravity.LEFT);

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,084评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,623评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,450评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,322评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,370评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,274评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,126评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,980评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,414评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,599评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,773评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,470评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,080评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,713评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,852评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,865评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,689评论 2 354

推荐阅读更多精彩内容