簡體   English   中英

如何在Android中添加Menuitem圖標

[英]How can add Menuitem Icon in android

這就是我在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;
            }
        });

我嘗試通過添加以下代碼行來添加圖標:

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

指定圖標的顯示方式作為與相應文本相鄰的菜單項圖標不可見。 有人可以幫忙嗎 謝謝

更新菜單項invalidateOptionsMenu()后,嘗試調用此方法。 如果您使用的是appcompat,請致電supportInvalidateOptionsMenu()

它應該解決你的問題。

在您的代碼中,嘗試將MenuItem.SHOW_AS_ACTION_NEVER更改為MenuItem.SHOW_AS_ACTION_ALWAYS並嘗試嘗試有關此操作的更多詳細信息,請參閱此鏈接。

這就是我的方式。 使用此代碼在此方向文件夾my_menutitem.xml >菜單下創建my_menutitem.xml文件。

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

在您的活動類中,使用此Override方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM