【问题标题】:How to display menu item with icon and text in AppCompatActivity如何在 AppCompatActivity 中显示带有图标和文本的菜单项
【发布时间】:2016-01-03 07:46:25
【问题描述】:

我在 xml 文件中尝试了不同的组合:

<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=".MainActivity">
    <item
        android:id="@+id/action_create_alarm"
        android:icon="@drawable/ic_action_accept"
        android:orderInCategory="100"
        android:title="@string/menu_create_alarm"
        app:showAsAction="ifRoom|withText" />
</menu>

<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=".MainActivity">
    <item
        android:id="@+id/action_create_alarm"
        android:icon="@drawable/ic_action_accept"
        android:orderInCategory="100"
        android:title="@string/menu_create_alarm"
        app:showAsAction="always|withText" />
</menu>

<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=".MainActivity">
    <item
        android:id="@+id/action_create_alarm"
        android:icon="@drawable/ic_action_accept"
        android:orderInCategory="100"
        android:title="@string/menu_create_alarm"
        app:showAsAction="withText" />
</menu>

<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=".MainActivity">
    <item
        android:id="@+id/action_create_alarm"
        android:icon="@drawable/ic_action_accept"
        android:orderInCategory="100"
        android:title="@string/menu_create_alarm"
        android:showAsAction="always|withText" />
</menu>

我尝试以编程方式设置它

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
        MenuItem item = menu.add(R.string.menu_create_alarm);
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT|MenuItem.SHOW_AS_ACTION_IF_ROOM);
        item.setIcon(R.drawable.ic_action_accept);
        item.setOnMenuItemClickListener(
            new OnMenuItemClickListener(){

                @Override
                public boolean onMenuItemClick(MenuItem item){
                    saveAlarm();
                    return true;
                }
            }
        );


//      inflater.inflate(R.menu.menu_create_alarm, menu);
        super.onCreateOptionsMenu(menu, inflater);

    }

<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=".MainActivity">
    <item
        android:id="@+id/action_create_alarm"
        android:icon="@drawable/ic_action_accept"
        android:orderInCategory="100"
        android:title="@string/menu_create_alarm"
        android:showAsAction="always|withText"
        app:showAsAction="always|withText" />
</menu>

但是,仅显示图标。并且有空间,因为我没有设置工具栏标题。删除菜单并用工具栏中的按钮替换它们是不合适的。
如何显示文字?

【问题讨论】:

  • @vab yo 链接到答案,解决方案已列出但无法正常工作
  • 图标+文字还是只有文字??
  • @XxGoliathusxX 图标+文字。
  • 你有一个菜单项吗?或多个

标签: android menuitem android-toolbar appcompatactivity


【解决方案1】:
@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_patient_home_screen, menu);


        menu.add(0, 1, 1, menuIconWithText(getResources().getDrawable(R.mipmap.user_2), getResources().getString(R.string.action_profile)));
        menu.add(0, 2, 2, menuIconWithText(getResources().getDrawable(R.mipmap.add_user), getResources().getString(R.string.action_add_user)));
        menu.add(0, 3, 3, menuIconWithText(getResources().getDrawable(R.mipmap.switch_profile), getResources().getString(R.string.action_switch_profile)));
        menu.add(0, 4, 4, menuIconWithText(getResources().getDrawable(R.mipmap.logout), getResources().getString(R.string.action_sign_out)));
        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
        switch (item.getItemId()) {
            case 1:
                Toast.makeText(PatientHomeScreen.this, "Profile is Clicked", Toast.LENGTH_SHORT).show();
                return true;
            case 2:
                Toast.makeText(PatientHomeScreen.this, "Add New User is Clicked", Toast.LENGTH_SHORT).show();
                return true;
            case 3:
                Toast.makeText(PatientHomeScreen.this, "Switch Profile is Clicked", Toast.LENGTH_SHORT).show();
                return true;
            case 4:
                Toast.makeText(PatientHomeScreen.this, "Sign Out is Clicked", Toast.LENGTH_SHORT).show();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private CharSequence menuIconWithText(Drawable r, String title) {

        r.setBounds(0, 0, r.getIntrinsicWidth(), r.getIntrinsicHeight());
        SpannableString sb = new SpannableString("    " + title);
        ImageSpan imageSpan = new ImageSpan(r, ImageSpan.ALIGN_BOTTOM);
        sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        return sb;
    }

希望对你有帮助

【讨论】:

  • 上述解决方案效果很好,如果您在 Fragment 中工作,您只需更改一件事,将 onCreateOptionsMenu(Menu menu) 更改为 onCreateOptionsMenu(Menu menu, MenuInflater inflater)。并在 onCreate(Bundle savedInstanceState) 或 View onCreateView(LayoutInflater inflater....) 中添加 setHasOptionsMenu(true)
【解决方案2】:

您需要在菜单标签中添加tools:context="your class"

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"
   xmlns:tools="http://schemas.android.com/tools"
   tools:context=".activities.BaseActivity">


   <item
       android:id="@+id/action_notification1"
       android:icon="@drawable/three"
       android:title="action_notification"
       app:showAsAction="always">
       <menu>
           <item
               android:id="@+id/profile"
               android:icon="@drawable/profile"
               android:orderInCategory="100"
               android:title="PROFILE" />

           <item
               android:id="@+id/c"
               android:icon="@drawable/correct_tick"
               android:orderInCategory="100"
               android:title="COMPLETED TRIPS" />

           <item
               android:id="@+id/app"
               android:icon="@drawable/report_issue"
               android:orderInCategory="100"
               android:title="REPORT ISSUES" />
           <item
               android:id="@+id/r"
               android:icon="@drawable/correct_tick"
               android:orderInCategory="100"
               android:title="REACHED CENTER" />


           <item
               android:id="@+id/pdf"
               android:icon="@drawable/pdf_image"
               android:orderInCategory="100"
               android:title="BAG INFO" />
           <item
               android:id="@+id/l"
               android:icon="@drawable/logout"
               android:orderInCategory="100"
               android:title="LOGOUT" />
       </menu>
   </item>


</menu>

覆盖onCreateOptionsMenu() 方法

@Override 
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu); 
    menu.getItem(0).getSubMenu().getItem(3).setVisible(false);
    menu.getItem(0).getSubMenu().getItem(4).setVisible(true);
    return super.onCreateOptionsMenu(menu);
} 

你应该写tool:context到菜单标签然后运行你会在你的文本之前得到图标。

【讨论】:

    【解决方案3】:

    添加到来自 dev_ry 的 answer,有一种更流畅的方式,无需使用反射,只需强制转换和抑制受限 API 警告:

    import android.support.v7.view.menu.MenuBuilder;
    
    @SuppressLint("RestrictedApi")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (menu instanceof MenuBuilder) {
            ((MenuBuilder) menu).setOptionalIconsVisible(true);
        }
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
    

    【讨论】:

    • 简单而强大的解决方案。
    • 拯救了我的一天兄弟 :-)
    【解决方案4】:
    protected boolean onPrepareOptionsPanel(View view, Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {
                    Log.e(getClass().getSimpleName(),
                            "onMenuOpened...unable to set icons for overflow menu",
                            e);
                }
            }
        }
        return super.onPrepareOptionsPanel(view, menu);
    }
    

    【讨论】:

    • 当我的班级扩展活动时,这对我有用:stackoverflow.com/a/22288914/555762。但是当我改变我的课程以扩展 AppCompatActivity 时,以前的解决方案停止工作,这个答案拯救了我的一天 =)
    • 非常感谢。我们需要对 proguard 进行哪些更改?
    • @Atul 我还没有为 proguard 测试过它,但不认为 progurad 需要因此而进行一些更改。
    • 尝试了其他所有方法以使图标和文本都显示在下拉菜单中。这个工作也给出了一个错误,通过在方法之前添加 @SuppressLint("RestrictedApi") 根据stackoverflow.com/questions/41150995/…
    【解决方案5】:

    xml:

    <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=".MainActivity">
        <item
            android:id="@+id/action_create_alarm"
            android:icon="@drawable/ic_action_accept"
            android:orderInCategory="100"
            android:title="@string/menu_create_alarm"
            android:showAsAction="always|withText"
            app:showAsAction="always|withText" />
    </menu>
    

    java:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(this).inflate(R.menu.menu_frg_safetybox, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }
    

    【讨论】:

    • 还是没有文字,只有图标
    • Android 最终会自行决定是否适合。
    • 如何调用,片段中的新充气机?如果我这样做 @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){ // inflater.inflate(R.menu.menu_create_level, menu); new MenuInflater(getActivity()).inflate(R.menu.menu_create_level, menu); super.onCreateOptionsMenu(menu, inflater); },我仍然只有图标
    • 如我所说。如果操作系统决定文本和图标对于设备来说太大,它只会放置图标。您必须尝试使用​​更大的设备。
    • 但是这和我的有什么不同呢哈哈.. stackoverflow 上的生活:)
    【解决方案6】:

    您可以使用以下代码来确定您的目的。无需使其程序化。您可以在 menu.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/overflowMenu"
        android:icon="@drawable/ic_more_vert_white_24dp"
        android:title=""
        app:showAsAction="always">
    
        <menu>
            <item
                android:id="@+id/menuWithIconText"
                android:icon="@drawable/chosen_icon"
                android:title="@string/menu_item_title"
                />
        </menu>
    </item>
    

    在上面的代码中,我们在item 中使用了menu。在内部菜单中,我们用图标定义了我们想要的溢出菜单。只要记住在item 标签之外使用app:showAsAction="always"

    【讨论】:

    • 我的项目中没有这样的drawable,当我添加它时它说它没有找到。
    • @SubqueryCrunch drawable 是您保存图标的文件夹。基本上在可绘制文件夹中,您保留所有资产。请检查您的资产文件夹并在 android:icon 属性中选择它。
    【解决方案7】:

    'always|withText' 如果有足够的空间会起作用,否则它只会放置图标。您可以通过将手机旋转到横向模式来查看.​​.

           <item
            android:id="@+id/action_create_alarm"
            android:icon="@drawable/ic_launcher"
            android:title="Save"
            app:showAsAction="always|withText"
            />
    

    【讨论】:

    • 这是正确的。如果我将设备设置为横向模式,则会显示文本。不过,我想一直显示文字。虽然我在工具栏中的标题很短(“活动”)文本没有出现。
    【解决方案8】:

    这两个一起试试

    app:showAsAction="always|withText"
    android:showAsAction="always|withText"
    

    【讨论】:

    • 还是没有文字,只有图标
    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
    • @JohanShogun 先生的链接在哪里
    • 这个是正确答案我不知道为什么它没有更多的赞成票
    【解决方案9】:

    MyActivity.java:

    @Override
        public boolean onCreateOptionsMenu(Menu menu) 
        {
            getMenuInflater().inflate(R.menu.my_menu, menu);
            View view = menu.findItem(R.id.whats_this).getActionView();
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // do something
                }
            });
            return super.onCreateOptionsMenu(menu);
        }
    

    my_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"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context=".MyActivity">
    
        <item
            android:id="@+id/item"
            app:actionLayout="@layout/my_layout"
            android:orderInCategory="100"
            android:title="@string/whats_this"
            app:showAsAction="always" />
    </menu>
    

    my_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:paddingLeft="5dp"
            android:gravity="center_vertical"
            android:textStyle="bold"
            android:textColor="@color/white"
            android:text="@string/whats_this"/>
    
        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:src="@mipmap/question"/>
    
    </LinearLayout>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多