简体   繁体   中英

How can add Menuitem Icon in android

This is how I have created my menuitem in android...

MenuItem archiveItem = menu.add(Menu.CATEGORY_SYSTEM, 0, 102, R.string.archive_events);
        archiveItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        archiveItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Intent intent = new Intent(MainActivity.this, PastEventsActivity.class);
                startActivity(intent);
                return false;
            }
        });

I tried adding an icon by putting the following line of code:

archiveItem.setIcon(getResources().getDrawable(R.drawable.ic_action_locate));

How come the specified icon is not visible as a menuitem icon adjacent to the respective text. Can someone help. Thanks

Try to call this method after update the menu item invalidateOptionsMenu() . If you are using appcompat then call supportInvalidateOptionsMenu()

It should solve your problem.

In your code try to change MenuItem.SHOW_AS_ACTION_NEVER to MenuItem.SHOW_AS_ACTION_ALWAYS and try it for more details about this see this link

This is the way i do. Use this code to Create a my_menutitem.xml file under this direction folder res -> menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item 
    android:id="@+id/action_date"      
    android:icon="@drawable/calender" //set ur icon here
    android:orderInCategory="9999"
    android:showAsAction="ifRoom" // change to always if u want to show always
    android:title="@string/CAL_title"/>

</menu>

In your activity class use this Override methods

  @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.my_menutitem, menu);
    return true;
}



@Override 
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_date:
        //do your code as u like
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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