繁体   English   中英

如何将菜单项添加到操作栏?

[英]How to add menu item to action bar?

我正在尝试将菜单项添加到操作栏。 菜单/main.xml:

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

    <item
        android:id="@+id/change_language"
        android:showAsAction="always"
        android:title="JP">
    </item>
    <item
        android:id="@+id/lists"
        android:icon="@android:drawable/ic_menu_agenda"
        android:showAsAction="always"
        android:title="Lists">
    </item>
    <item
        android:id="@+id/collections"
        android:icon="@android:drawable/ic_menu_star"
        android:showAsAction="ifRoom"
        android:title="Collections">
    </item>

</menu>

change_language,列出项目运行良好。 菜单项“收藏”未显示

MainActivity.java

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    menu.findItem(R.id.change_language).setTitle("JP");
    return true;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

它没有给出任何错误。 我已经检查了R.java。 没有提到“集合”。 在编写“ R.id”时,智能许可证也没有给出提示。如何将菜单项添加到操作栏中? 也许是因为我将应用发布到了Google Play。 但是,我将Debuggable设置为'true'。

上面的showAsAction属性使用标记中定义的自定义名称空间。 使用支持库定义的任何XML属性时,这是必需的,因为这些属性在旧设备的Android框架中不存在。 因此,您必须使用自己的名称空间作为支持库定义的所有属性的前缀。

因此,将其添加到标签'xmlns:yourapp =“ http://schemas.android.com/apk/res-auto”'

并按如下所示设置showAsAction属性:yourapp:showAsAction =“ always”

R.java不包含id.collections ,它仅包含main.xml ,如下所示:

public static final class menu {
    public static final int main=0x7f0e0000;
}

另外,您的应用发布与此问题无关。

您的R.id.change_language在哪里? 如果要创建带有图标和标题的自定义操作栏,则必须修改main.xml并添加如下自定义布局:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:id="@+id/collection"
    android:actionLayout="@layout/your_custom_layout"
    android:showAsAction="ifRoom|withText"
    android:title="ActionBar"/>

</menu>

your_custom_layout.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<ImageView
    android:id="@+id/your_imageview"
    android:background="@android:drawable/ic_menu_star" />

<TextView 
    android:id="@+id/change_language"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</RelativeLayout>

然后,你可以findViewByIdonCreateOptionsMenu功能。

希望这会有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM