web-dev-qa-db-fra.com

Comment afficher un élément de menu avec une icône et du texte dans AppCompatActivity

J'ai essayé différentes combinaisons dans un fichier 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>

ou

<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>

ou

<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>

ou

<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>

J'ai essayé de le définir par programme

@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);

    }

ou

<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>

Cependant, seule l'icône apparaît. Et il y a beaucoup de place, car je n’ai pas défini le titre de la barre d’outils. Supprimer des menus et les remplacer par un bouton dans la barre d’outils n’est pas raisonnable.
Comment afficher du texte?

27
Yarh

Vous devez ajouter tools:context="your class" À la balise de menu

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>

Substitution onCreateOptionsMenu() Méthode

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

Vous devriez écrire tool:context Dans la balise de menu puis exécuter, vous obtiendrez des icônes avant votre texte.

23
Raj Kumar
@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;
    }

Screen shot of emulator

J'espère que ceci vous aidera

19
Harshal Pathak
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);
}
12
Ravi Yadav

En ajoutant réponse de dev_ry, il existe un moyen beaucoup plus fluide de ne pas utiliser la réflexion en diffusant et en supprimant simplement l'avertissement de l'API restreinte:

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);
}
10
Maxr1998

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);
}
8
Nicolas Tyler

'always | withText' fonctionnera s'il y a suffisamment de place, sinon il ne placera que l'icône. Vous pouvez le voir en faisant pivoter le téléphone en mode paysage ..

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

essayez ces deux ensemble

app:showAsAction="always|withText"
Android:showAsAction="always|withText"
1
Elltz