【问题标题】:How do I add items to GWT ListBox in Uibinder .ui.xml template ?如何在 Uibinder .ui.xml 模板中向 GWT ListBox 添加项目?
【发布时间】:2024-01-16 20:49:02
【问题描述】:

如何使用 UiBinder 添加列表框项?

【问题讨论】:

  • code.google.com/webtoolkit/doc/latest/… 展示了如何从 Java 文件中添加 ListBox 项,不过我想您是在询问是否可以在 UiBinder 模板中指定它们。
  • 是的....我在问我们是否可以在 uibinder 本身中提供项目

标签: gwt listbox uibinder


【解决方案1】:

从 2011 年 2 月版本开始有可能:

http://code.google.com/p/google-web-toolkit/issues/detail?id=4654

按照this patch,您现在可以按照以下语法添加项目:

<g:ListBox>
  <g:item value='1'>
    first item
  </g:item>
  <g:item value='2'>
    second item
  </g:item>
</g:ListBox>

【讨论】:

    【解决方案2】:

    这是一个枚举翻译的列表框,我想这也适用于带有字符串值的列表框(GWT 版本:2.1.0)

    您只需要渲染器来翻译枚举值。

    //UI XML

     <g:ValueListBox ui:field="requesterType"/> 
    

    //JAVA代码

     @UiField(provided = true)
     ValueListBox<RequesterType> requesterType = new ValueListBox<RequesterType>(requesterTypeRenderer);
    
     static EnumRenderer<RequesterType> requesterTypeRenderer = new EnumRenderer<RequesterType>();
    
     public Constructor() {
         requesterTypeRenderer.setEmptyValue(Translations.translateEmptyValue(RequesterType.class));
         requesterType.setAcceptableValues(Arrays.asList(EnumUtil.getRequesterTypes()));
     }
    

     /**
      * Translates enum entries. Use setEmptyValue() if you want to have a custom empty value. Default empty value is "".
      * 
      * @param <T>
      *            an enumeration entry which is to be registered in {@link Translations}
      */
    
    public class EnumRenderer<T extends Enum<?>> extends AbstractRenderer<T> {
    
       private String emptyValue = "";
    
       @Override
       public String render(T object) {
           if (object == null)
               return emptyValue;
           return Translations.translate(object);
       }
    
       public void setEmptyValue(String emptyValue) {
           this.emptyValue = emptyValue;
       }
    
    }
    

    【讨论】:

    • Gunnie,您如何将您的解决方案与here 描述的声明性国际化结合起来?
    【解决方案3】:

    GWT ValueListbox 也称为 ComboBox 或 Dropdown 组件。 另一个也演示填充列表的示例。

    UiBinder...

    <g:ValueListBox ui:field="subCategory"/> 
    

    编辑器...

    @UiField(provided = true)
    ValueListBox<String> subCategory = new ValueListBox<String>(
      new Renderer<String>() {
    
        @Override
        public String render(String object) {
          String s = "Cats";
          if (object != null) {
            s = object.toString();
          }
          return s;
        }
    
        @Override
        public void render(String object, Appendable appendable)
            throws IOException {
          render(object);
        }
    
    });
    

    构造函数...

    List<String> values = new ArrayList<String>();
    values.add("Animal Shelters and Rescues");
    values.add("Birds");
    values.add("Cats");
    values.add("Dogs");
    values.add("Other Pets");
    values.add("Rabbits");
    subCategory.setAcceptableValues(values);
    

    【讨论】: