代码改变世界

UiBinder小试牛刀

2009-11-20 22:36  小寇子  阅读(786)  评论(0)    收藏  举报
public interface UiBinder<U,O>

Interface implemented by classes that generate DOM or Widget structures from ui.xml template files, and which inject portions of the generated UI into the fields of an owner.

The generated UiBinder implementation will be based on an xml file resource in the same package as the owner class, with the same name and a "ui.xml" suffix. For example, a UI owned by class bar.baz.Foo will be sought in /bar/baz/Foo.ui.xml. (To use a different template file, put the UiTemplate annotation on your UiBinder interface declaration to point the code generator at it.)

实现UiBinder的类必须与xml的资源文件在同一包下,并且名字必须跟ui.xml前的名字一样.

例如:一个被类bar.baz.Foo拥有的UI,会在/bar/baz/Foo.ui.xml里寻找.想用一个其他的模板文件,需要把UiTemplate注释加到你的UiBinder接口的声明里来指向它.(应该是想指定一个名字不相同的ui.xml模板的时候用)

 UcreateAndBindUi(O owner) 
          Creates and returns the root object of the UI, and fills any fields of owner tagged with UiField.

创建一个顶级UI的对象,并且把owner里标记为UiField的字段对应上,然后返回这个UI Object.

Mail里的 例子看下:
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
    xmlns:g='urn:import:com.google.gwt.user.client.ui' 
    xmlns:mail='urn:import:com.google.gwt.sample.mail.client'>
AboutDialog.ui.xml
<ui:style>
    .aboutText 
    {
        padding: 10px;
        text-align: left;
    }
</ui:style>

<g:HTMLPanel width='24em'>
<div class='{style.aboutText}'>
    This sample application demonstrates the
    construction of a complex user interface using GWT's built-in
    widgets. Have a look at the code to see how easy it is to build
    your own apps!
    </div>
<g:Button text='Close' ui:field='closeButton' />
</g:HTMLPanel>
</ui:UiBinder>


AboutDialog.java
public class AboutDialog extends DialogBox {

  interface Binder extends UiBinder<Widget, AboutDialog> { }//将ui.xml里的封装成Widget然后绑定                    到AboutDialog类里
  private static final Binder binder = GWT.create(Binder.class);
    
  @UiField Button closeButton;//与<g:Button text='Close' ui:field='closeButton' />对应

  public AboutDialog() {
    // Use this opportunity to set the dialog's caption.
    setText("About the Mail Sample");
    setWidget(binder.createAndBindUi(this));

    setAnimationEnabled(true);
    setGlassEnabled(true);
  }

  @Override
  protected void onPreviewNativeEvent(NativePreviewEvent preview) {
    super.onPreviewNativeEvent(preview);

    NativeEvent evt = preview.getNativeEvent();
    if (evt.getType().equals("keydown")) {
      // Use the popup's key preview hooks to close the dialog when either
      // enter or escape is pressed.
      switch (evt.getKeyCode()) {
        case KeyCodes.KEY_ENTER:
        case KeyCodes.KEY_ESCAPE:
          hide();
          break;
      }
    }
  }

  @UiHandler("closeButton")
  void onSignOutClicked(ClickEvent event) {
    hide();
  }
}
运行后生成的UI Object



 Eclipse插件可以直接新建UiBinder,可以选择生成的UI绑定到Composite或UIObject的子类

主要用到的源注释:
UiConstructor 
UiFactory 
UiField 
UiHandler 
UiTemplate