Android之Menu解析

菜單資源文件放在res/menu目錄,使用menu標籤作爲根節點。

  • item 菜單項
  • group 分組
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.menu.MainActivity" >
    <item android:id="@+id/action_setting1"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />
    <item android:id="@+id/action_setting2"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />
    <item android:id="@+id/action_setting3"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>

item標籤內的屬性

android:id="@+id/menu_item"
android:actionLayout="layout"
android:actionProviderClass="class"
android:actionViewClass="class"
android:alphabeticShortcut="string"
android:numericShortcut="string"
android:checkable="true|false"
android:checked="true|false"
android:enabled=true|false""
android:icon="@mipmap/ic_launcher"
android:menuCategory="container|system|secondary|alternative"
android:onClick="method"
android:orderInCategory="integer"
android:title="string"
android:titleCondensed="string"
android:visible="trur|false"
app:showAsAction="always|ifRoom|never|withText|collapseActionView"

屬性:

  • android:id 定義資源ID,它是個唯一值
  • android:title 定義菜單的標題
  • android:titleCondensed 定義一個簡要的標題,在普通的標題太長時來使用
  • android:icon 它定義了一個菜單項的圖標
  • android:onClick 方法名。在這個菜單項被點擊時,會調用這個方法。在Activity中,這個方法必須用public關鍵字來聲明,並且只接受一個MenuItem對象,這個對象指明瞭被點擊的菜單項。這個方法會優先標準的回調方法:onOptionsItemSelected()

    注意:如果要使用ProGuard(或類似的工具)來混淆代碼,就要確保不要重名這個屬性所指定的方法,因爲這樣能夠破壞功能。
    這個屬性在API級別11中被引入。
    
  • android:showAsAction 關鍵詞。定義這個項目作爲操作欄中的操作項的顯示時機和方式。只用Activity包含了一個ActionBar對象時,菜單項才能夠作爲操作項來顯示。這個屬性在API級別11中被引入,有效值如下:

    ifRoom 如果有針對這個項目的空間,則只會把它放到操作欄中
    
    withText 操作項也要包含文本(通過android:title屬性來定義的)。可以把這個值與其他的Flag設置放到一起,通過管道符“|”來分離它們。
    
    never 這個項目不會放到操作欄中
    
    always 始終包這個項目放到操作欄中。要避免使用這個設置,除非在操作欄中始終顯示這個項目是非常關鍵的。
    設置多個項目作爲始終顯示的操作項會導致操作欄中其他的UI溢出。
    
    collapseActiionView 它定義了跟這個操作項關聯的可摺疊的操作View對象(用android:actionViewLayout來聲明)。
    這個關鍵詞在API級別14中被引入。
    
  • android:actionViewLayout 引用一個佈局資源,這個佈局要用於操作窗口。更多的信息請參照“操作欄”開發指南。這個屬性在API級別11中被引入。

  • android:actionViewClass 定義了操作窗口要使用的View對象的完整的類名。例如,“android.widget.SearchView”說明操作窗口要使用的SearchView類。
    這個屬性在API級別11中被引入
  • android:actionProviderClass 操作項目所使用的ActionProvider類的完整的類名。例如,“android.widget.ShareActionProvider”說明要使用ShareActionProvider類

    注意:如果要使用ProGuard(或類似的工具)來混淆代碼,就要確保不要重名這個屬性所指定的方法,因爲這樣能夠破壞功能。
    這個屬性在API級別14中被引入
    
  • android:alphabeticShortcut 定義一個字符快捷鍵
  • android:numericShortcut 定義一個數字快捷鍵
  • android:checkable 如果菜單項是可以複選的,那麼就設置爲true。
  • android:checked 如果複選菜單項默認是被選擇的,那麼就設置爲true。
  • android:visible 如果菜單項默認是可見的,那麼就設置爲true。
  • android:enabled 如果菜單項目默認是可用的,那麼就設置爲true。
  • android:menuCategory 關鍵詞。它的值對應了定義菜單項優先級的CATEGORE_*常量,有效值如下:

    Container 菜單項是容器的一部分
    
    system 菜單項是由系統提供的。
    
    secondary 提供給用戶的輔助選擇的菜單項(很少使用)
    
    alternative 基於當前顯示的數據來選擇操作的菜單項。
    
  • android:orderInCategory 整數值,它定義菜單項在菜單組中的重要性的順序。

Group標籤內的屬性

android:id="@+id/group1"
android:checkableBehavior="none|all|single"
android:enabled="trur|false"
android:menuCategory="container|system|secondary|alternative"
android:orderInCategory="integer"
android:visible="trur|false"

屬性:

  • android:id 定義資源ID,它是個唯一值
  • android:checkableBeharior 關鍵詞。針對菜單組的可複選行爲的類型。有效值如下:

    none 沒有可複選性
    all 組內的所有的項目都被複選(使用複選框)
    single 僅有一個項目能夠被複選(使用單選按鈕)
    
  • android:enabled 如果菜單組默認是可用的,那麼就設置爲true。
  • android:menuCategory 關鍵詞。它的值對應Menu類的CATEGORY_*常量,定義了菜單組的優先級。有效值如下:

    container 菜單組是容器的一部分
    system 菜單組是由系統提供的。
    secondary 提供給用戶的輔助選擇的菜單組(很少使用)
    alternative 基於當前顯示的數據來選擇操作的菜單組。
    
  • android:orderInCategory 整數值,它定義了分類中菜單項目的默認順序。

  • android:visible 如果菜單組默認是可見的,那麼就設置爲true。

定義Menu的兩種方法(在onCreateXXXMenu方法內實現)

方法一 在Android代碼中,使用Menu類中的add方法(Menu類中提供了相關屬性的定義方法,add()添加item項)

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // add(int groupId, int itemId, int order, CharSequence title);
        menu.add(Menu.NONE, Menu.NONE, 1, "item1");
        menu.add(Menu.NONE, Menu.NONE, 2, "item2");
        menu.add(Menu.NONE, Menu.NONE, 3, "item3");
        return true;
    }

方法二 使用menu資源文件

    @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);
        return true;
    }

Android中的三種Menu

OptionsMenu(一般在ActionBar中使用)

實現步驟:

  1. 在佈局文件中添加:

    <android.support.design.widget.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
    </android.support.design.widget.AppBarLayout>
    
  2. 在Activity的onCreate方法中

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    
  3. 重寫onCreateOptionsMenu方法,實現menu定義

  4. 重寫onOptionsItemSelected方法,實現item的點擊事件監聽

實例

@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);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

效果圖:

PopupMenu

實現步驟:

  1. create a new popup menu with an anchor view

    PopupMenu popupMenu=new PopupMenu(Context context, View anchor);
    
  2. 定義menu

    popupMenu.getMenuInflater().inflate(R.menu.popup_menu,popupMenu.getMenu());
    
  3. 爲popupmenu添加點擊事件的監聽

    popupMenu.setOnMenuItemClickListener
    

實例:

btnPopupMenu = (Button) findViewById(R.id.btn_popup);
    btnPopupMenu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PopupMenu popupMenu=new PopupMenu(MainActivity.this, btnPopupMenu);
            popupMenu.getMenuInflater().inflate(R.menu.popup_menu,popupMenu.getMenu());
            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    Toast.makeText(MainActivity.this, item.getTitle(), Toast.LENGTH_SHORT).show();
                    return true;
                }
            });
            popupMenu.show();
        }
    });

效果圖:

ContextMenu

實現步驟:

  1. registerForContextMenu(View view); 註冊要爲給定視圖顯示的ContextMenu
  2. 重寫onCreateContextMenu方法,實現menu定義
  3. 重寫onContextItemSelected方法,實現item的點擊事件監聽

實例:

public class ContextMenuActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_context_menu);
        ListView lv_context= (ListView) findViewById(R.id.lv_context);
        String[] data={"item1","item2","item3","item4"};
        ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,data);
        lv_context.setAdapter(adapter);
        //註冊要爲給定視圖顯示的ContextMenu
        registerForContextMenu(lv_context);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        //設置菜單佈局
        menu.setHeaderIcon(R.mipmap.ic_launcher_round);
        menu.setHeaderTitle("Select the action");
        menu.add(0,v.getId(),0,"delete");
        menu.add(0,v.getId(),0,"upper");
        menu.add(0,v.getId(),0,"lower");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getTitle()=="delete"){
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
        }else if (item.getTitle()=="upper"){
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
        }if (item.getTitle()=="lower"){
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
        }
        return true;
    }
}

效果圖:

發佈了36 篇原創文章 · 獲贊 20 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章