Android之Menu解析

来源:互联网 发布:php好找工作么 编辑:程序博客网 时间:2024/06/06 01:16

菜单资源文件放在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的点击事件监听

实例

@Overridepublic 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;}@Overridepublic 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;    }}

效果图:

原创粉丝点击