美文网首页
How to create menu in activity?

How to create menu in activity?

作者: JayZhaoCN | 来源:发表于2017-05-30 16:16 被阅读0次

1. 创建menu目录

首先需要在layout目录下创建menu目录:

创建menu目录

2. 创建xml文件

menu目录下创建xml文件,每一个xml文件对应一个menu.

xml文件如何创建,下面给了一个例子:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/item_day"
        android:orderInCategory="100"
        android:title="@string/day_chart"
        app:showAsAction="never"/>

    <item
        android:id="@+id/item_week"
        android:orderInCategory="100"
        android:title="@string/week_chart"
        app:showAsAction="never"/>

    <item
        android:id="@+id/item_month"
        android:orderInCategory="100"
        android:title="@string/month_chart"
        app:showAsAction="never"/>

    <item
        android:id="@+id/item_year"
        android:orderInCategory="100"
        android:title="@string/year_chart"
        app:showAsAction="never"/>

</menu>

PS: Android Studio非常贴心的为menu下的xml文件也创建了预览视图:

menu下xml文件的预览界面
属性解释

app:showAsAction="never":永远不会显示。只会在溢出列表中显示,而且只显示标题,所以在定义item的时候,最好把标题都带上。
app:showAsAction="always" 无论是否溢出,总会显示。
app:showAsAction="ifRoom":如果有位置才显示,不然就出现在右边的三个点中。

android:orderInCategory="100"
设置优先级,值越大优先级越低

3. 在Activity中复写相关代码

需要复写两个方法,直接上代码了:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.some_menu, 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);
    }
onOptionsItemSelected()返回值解释:

return super.onOptionsItemSelected(item):对没有处理的事件,交给父类来处理。
return true:表示处理完菜单项的事件,不需要将该事件继续传播。

补充

关于为menu添加iconAndroid4.0及以后已经默认icon是不显示的,具体可以看这篇文章:
http://blog.csdn.net/csdn_blog_lcl/article/details/52596830


以上

相关文章

网友评论

      本文标题:How to create menu in activity?

      本文链接:https://www.haomeiwen.com/subject/rherfxtx.html