您可以将处理程序添加到 CellTree 的 TreeViewModel 的 NodeInfo 中。
这是如何做到的示例:
首先让我们定义什么是文件夹:
// the simplest possible folder even without subfolders just to make example working
public class Folder {
private String name;
public Folder(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
假设您的 ui.xml 的一部分如下:
<g:HorizontalPanel>
<cellview:CellTree ui:field="folderTree"/>
<g:Label ui:field="folderName"/>
</g:HorizontalPanel>
比你有 UiBinder:
public static interface Binder extends UiBinder<HorizontalPanel, BinderOwner> {}
下面是定义 CellTree 所需的 FolerTreeModel 的方法:
public static class FolderTreeModel implements TreeViewModel {
private final ListDataProvider<Folder> dataProvider;
private final CellPreviewEvent.Handler<Folder> folderSelectionHandler;
public FolderTreeModel(List<Folder> folders, CellPreviewEvent.Handler<Folder> folderSelectionHandler) {
this.folderSelectionHandler = folderSelectionHandler;
dataProvider = new ListDataProvider<Folder>(folders);
}
@Override
public <T> TreeViewModel.NodeInfo<?> getNodeInfo(T value) {
return new DefaultNodeInfo<Folder>(dataProvider, new AbstractCell<Folder>() {
// simple renderer that renders folder name
@Override
public void render(Context context, Folder value, SafeHtmlBuilder sb) {
sb.appendEscaped(value.getName());
}
},
new SingleSelectionModel<Folder>(), // using single selection model
folderSelectionHandler, // add handler to the node info
null); // value updater can be null
}
@Override
public boolean isLeaf(Object value) {
return false; // I will say that every node is not leaf for simplicity
}
}
还有你的 BinderOwner 类:
public static class BinderOwner {
@UiField(provided = true)
CellTree folderTree;
@UiField
Label folderName; //your other UI element that you will change: show the name of selected folder
public BinderOwner() {
//List of folders to show something
ArrayList<Folder> folders = new ArrayList<Folder>();
folders.add(new Folder("A"));
folders.add(new Folder("B"));
folders.add(new Folder("C"));
// define folder tree
folderTree = new CellTree(new FolderTreeModel(folders, new CellPreviewEvent.Handler<Folder>() {
// this is your handler
@Override
public void onCellPreview(CellPreviewEvent<Folder> event) {
// set folder name to label on folder selection
folderName.setText(event.getValue().getName());
}
}), null);
}
}