4

How can I get add an icon with text to a menu item in GWT? The following does not work:

<ui:with field='res' type='my.package.MyResources' />
<g:MenuItem text="test"><g:Image resource="{res.myIcon}" /></g:MenuItem>

Resulting error:

Not allowed in an HTML context: <g:Image resource='{res.myIcon}'>

public interface MyResources extends ClientBundle {
  @Source("myIcon.png")
  ImageResource myIcon();
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120

3 Answers3

3

The MenuItem allows only HTML or plain text as its content. So you cannot use an Image widget, but you can very well use an <img> element and retrieve the image URL from the ImageResource referenced by <ui:with> using getSafeUri() (you can call no-arg methods in UiBinder templates). In your case:

<g:MenuItem>
  <img src="{res.myIcon.getSafeUri}"/><span>Your text here</span>
</g:MenuItem>

Or programmatically, using a simple template:

public interface MyTemplate extends SafeHtmlTemplates {
  @Template("<img src=\"{0}\" /><span>{1}</span>")
  SafeHtml createItem(SafeUri uri, SafeHtml message);
}

instantiated via:

MyTemplate template = GWT.create(MyTemplate.class)

and used like so:

new MenuItem(template.createItem(
    yourResources.myIcon().getSafeUri(),
    SafeHtmlUtils.fromString("Your text here")));
Andrea Boscolo
  • 3,038
  • 1
  • 16
  • 21
0

Please try this

  <g:MenuItem>
    <div class="className"/> MyMenuWithImg
  </g:MenuItem>

That css class have the background image.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

I ended up extending the GWT MenuItem class in a way that one can supply an ImageResource from ui-binder:

class MyMenuItem extends MenuItem {
    @Uresstructor
    public resMenuItem(String text, ImageResource res) {
        super(SafeHtmlUtils.fromString(text));

        ImageResourceRenderer renderer = new ImageResourceRenderer();
        setHTML(renderer.render(res) + "&nbsp;" + text);
    }
}

Usage:

<ui:with field='res' type='path.to.MyIconResources' />

<g:MenuBar>
 <my:MyMenuItem text="test" icon="{res.myIcon}" />
</g:MenuBar>

If anyone comes up with a better idea (now or in the future) please comment accordingly.

membersound
  • 81,582
  • 193
  • 585
  • 1,120