Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

popupmenu - Android setIcon function for Popup Menu not displaying my drawable

I'm trying to dynamically create a Popup Menu using Android's built-in PopupMenu class. No matter what I try, I'm unable to get the setIcon function to display anything. I've pared down my code to a pretty simple example:

public void showPopupMenu(View v) {
    popupMenu = new PopupMenu(this, v);
    popupMenu.setOnMenuItemClickListener(this);
    MenuItem menuItem = popupMenu.add("Menu Item 1");
    menuItem.setIcon(DrawableResource);
    popupMenu.show();
}

The menu shows up with only the text of the menu item. The resolution of the drawable is 40x40. If I try the same thing from XML, the icon shows up just fine. Any help figuring out what might be wrong is appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I note an error in the value passed to the setIcon method. You need to get your drawable resource image by doing

menuItem.setIcon(R.drawable.NameOfYourDrawableFile);

For instance, if the name of your drawable resource image is image.png, then you should do:

menuItem.setIcon(R.drawable.image);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...