Android Menu 匯總

作者:Otway
版權(quán):轉(zhuǎn)載請(qǐng)注明出處!

選項(xiàng)菜單 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" />
    

    通過(guò) setOnActionExpandListener() 監(jiān)聽(tīng)展開(kāi)收縮事件

  • 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"
        />
    

    顯示布局及可以監(jiān)聽(tīng)相關(guān)事件

    @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);
                //沒(méi)有第三方可以分享,可以自定義
                //如果一個(gè)應(yīng)用程序需要接受Share Intent發(fā)送的共享數(shù)據(jù)棒妨,
                // 那么需要在該應(yīng)用程序的Manifest.xml文件中定義<intent-filter/>元素 
                 //android.intent.action.SEND,
                // 指明應(yīng)用組件想要接受的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();
            //檢查手機(jī)上是否存在可以處理這個(gè)動(dòng)作的應(yīng)用
            List<ResolveInfo> infoList = pm.queryIntentActivities(shareIntent, 0);
            if (!infoList.isEmpty()) {
                mShareActionProvider.setShareIntent(shareIntent);
                return true;
            }
            return false;
        }
        return false;
    }
    

    這種會(huì)記錄偏好含长,可通過(guò)setShareHistoryFileName()設(shè)置記錄的xml文件名

    設(shè)置setOnShareTargetSelectedListener監(jiān)聽(tīng)條目點(diǎn)擊事件

    可繼承support包下ActionProvider自定義實(shí)現(xiàn)
    android.support.design.R.dimen.abc_action_bar_default_height_material

關(guān)于overflow menu在高版本不顯示icon

安卓4.0之前會(huì)顯示icon券腔,高版本中不會(huì)顯示,可以通過(guò)反射去設(shè)置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實(shí)現(xiàn)Menu接口拘泞,創(chuàng)建菜單時(shí)纷纫,傳進(jìn)來(lái)的menu其實(shí)就是MenuBuilder對(duì)象                
                    m.invoke(menu, enable);
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }
    /**
     *  android 4.0以后使用AppCompatActivity必須在該方法中調(diào)用setIconEnable(),
     *  隱藏的menuitem的icon才會(huì)顯示
     *  android 4.0以后其他的activity可以再onPrepreOptionMenu()中調(diào)用
     *  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);
    }

手機(jī)實(shí)體菜單按鍵導(dǎo)致actionbar上的三個(gè)點(diǎn)圖標(biāo)不顯示

    /**
     * 通過(guò)反射陪腌,設(shè)置實(shí)體menu鍵可用與否
     * 該方法在onCreate()中調(diào)用
     * @param enable  false:實(shí)體鍵不可用辱魁,會(huì)在actionbar上顯示小點(diǎn) 
     *                true:可用,點(diǎn)擊menu實(shí)體鍵才會(huì)顯示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) {
        }
    }

可以通過(guò)自定義toolbar中布局實(shí)現(xiàn)理想效果

    ActionBar actionBar = getSupportActionBar();
    //設(shè)置自定義actionbar的view
    actionBar.setCustomView(R.layout.action_bar_layout);
    //設(shè)置展示的options為DISPLAY_SHOW_CUSTOM
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    //設(shè)置showCustom為true
    actionBar.setDisplayShowCustomEnabled(true);
    

上下文菜單 ContextMenu

浮動(dòng)上下文菜單

  • registerForContextMenu(View view)注冊(cè)于上下文菜單關(guān)聯(lián)的View

  • ActivityFragment實(shí)現(xiàn) registerForContextMenu()诗鸭,當(dāng)關(guān)聯(lián)的View收到長(zhǎng)按事件之后染簇,會(huì)響應(yīng)該方法。

    @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);
    }
    
    
  • 事件監(jiān)聽(tīng)

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

為單個(gè)視圖啟用上下文操作模式

  • 實(shí)現(xiàn) ActionMode.Callback 接口强岸。在其回調(diào)方法中锻弓,您既可以為上下文操作欄指定操作,又可以響應(yīng)操作項(xiàng)目的點(diǎn)擊事件蝌箍,還可以處理操作模式的其他生命周期事件
  • 當(dāng)需要顯示操作欄時(shí)青灼,調(diào)用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();
    }

通過(guò)setOnMenuItemclickListener()設(shè)置監(jiān)聽(tīng)

基于 Intent 的菜單項(xiàng)

通過(guò)intent_filter定義刪選規(guī)則 CATEGORY_ALTERNATIVECATEGORY_SELECTED_ALTERNATIVE

調(diào)用Menu.addIntentOptions()來(lái)添加應(yīng)用列表

ListPopupMenu

    final ListPopupWindow popup = new ListPopupWindow(mContext);
    List<String> list = new ArrayList<>();
    list.add("不喜歡");
    list.add("舉報(bào)");
    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);

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末暴心,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子杂拨,更是在濱河造成了極大的恐慌专普,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件弹沽,死亡現(xiàn)場(chǎng)離奇詭異檀夹,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)贷币,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門(mén)击胜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)亏狰,“玉大人役纹,你說(shuō)我怎么就攤上這事∠就伲” “怎么了促脉?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)策州。 經(jīng)常有香客問(wèn)我瘸味,道長(zhǎng),這世上最難降的妖魔是什么够挂? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任旁仿,我火速辦了婚禮,結(jié)果婚禮上孽糖,老公的妹妹穿的比我還像新娘枯冈。我一直安慰自己,他們只是感情好办悟,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布尘奏。 她就那樣靜靜地躺著,像睡著了一般病蛉。 火紅的嫁衣襯著肌膚如雪炫加。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,301評(píng)論 1 301
  • 那天铺然,我揣著相機(jī)與錄音俗孝,去河邊找鬼。 笑死魄健,一個(gè)胖子當(dāng)著我的面吹牛赋铝,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播诀艰,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼柬甥,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼饮六!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起苛蒲,我...
    開(kāi)封第一講書(shū)人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤卤橄,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后臂外,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體窟扑,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年漏健,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了嚎货。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蔫浆,死狀恐怖殖属,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情瓦盛,我是刑警寧澤洗显,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站原环,受9級(jí)特大地震影響挠唆,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜嘱吗,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一玄组、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧谒麦,春花似錦俄讹、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至迁匠,卻和暖如春剩瓶,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背城丧。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工延曙, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人亡哄。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓枝缔,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子愿卸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • ¥開(kāi)啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開(kāi)一個(gè)線程灵临,因...
    小菜c閱讀 6,409評(píng)論 0 17
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,110評(píng)論 25 707
  • 2017年5月17日 Kylin_Wu 標(biāo)注(★☆)為考綱明確給出考點(diǎn)(必考) 常見(jiàn)手機(jī)系統(tǒng)(★☆) And...
    Azur_wxj閱讀 1,811評(píng)論 0 10
  • 明天六點(diǎn)起床,想著就要哭了趴荸。
    citoyendumonde閱讀 158評(píng)論 0 0
  • 勤奮在形容一個(gè)人往往是褒義詞儒溉,但是太過(guò)勤奮,效率很可能是不高的发钝,這樣就會(huì)導(dǎo)致事倍功半顿涣,人類的每個(gè)發(fā)明并不是讓人變得...
    Betterman1057閱讀 583評(píng)論 0 1