我正在尝试使SuggestBox仅在输入2个字符后显示建议。我的想法是使用DefaultSuggestionDisplay类在文本长度为1时隐藏建议。我试图在SuggestionBox本身及其TextBox上附加不同的处理程序,如KeyPressHandler和KeyUpHandler,但它们似乎都不起作用。你有任何建议"? :d
答案 0 :(得分:0)
您可以扩展SuggestBox并覆盖showSuggestionList()
方法。
添加KeyUpHandler无法正常工作,因为您添加了另一个KeyUpHandler,而不是替换SuggestBox添加到其自己的TextBox中的那个。
编辑:
@Override
showSuggestionList() {
if (getTextBox().getValue().length() > 1) {
super.showSuggestionList();
}
}
答案 1 :(得分:0)
您可以扩展DefaultSuggestionDisplay
并覆盖showSuggestions
方法:
public class MySuggestionDisplay extends DefaultSuggestionDisplay {
@Override
protected void showSuggestions(SuggestBox suggestBox, Collection<? extends Suggestion> suggestions, boolean isDisplayStringHTML, boolean isAutoSelectEnabled, SuggestionCallback callback) {
if(suggestBox.getText().length() > 1)
super.showSuggestions(suggestBox, suggestions, isDisplayStringHTML, isAutoSelectEnabled, callback);
}
}
您必须将新显示传递给SuggestBox
构造函数:
public class MySuggestBox extends SuggestBox {
public MySuggestBox() {
super(
new MySuggestOracle(),
new TextBox(),
new MySuggestionDisplay());
}
}
在此构造函数中,您应该提供:
SuggestOracle
班级(此处名为MySuggestOracle
) - 我想您有一个TextBox
- 这是输入文字的默认小部件(您可以自己提供,只需要实现HasText
)SuggestionDisplay
- 使用覆盖showSuggestions
方法的方法。这是完整的工作示例代码,显示至少输入2个字符的建议:
import java.util.ArrayList;
import java.util.Collection;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.google.gwt.user.client.ui.TextBox;
public class MySuggestBox extends SuggestBox {
public MySuggestBox() {
super(
new SuggestOracle() {
@Override
public void requestSuggestions(Request request, Callback callback) {
ArrayList<Suggestion> suggestions = new ArrayList<Suggestion>();
suggestions.add(new MySuggestion("aaa"));
suggestions.add(new MySuggestion("bbb"));
suggestions.add(new MySuggestion("ccc"));
suggestions.add(new MySuggestion("ddd"));
Response response = new Response();
response.setSuggestions(suggestions);
callback.onSuggestionsReady(request, response);
}
},
new TextBox(),
new MySuggestionDisplay());
}
public static class MySuggestionDisplay extends DefaultSuggestionDisplay {
@Override
protected void showSuggestions(SuggestBox suggestBox, Collection<? extends Suggestion> suggestions, boolean isDisplayStringHTML, boolean isAutoSelectEnabled, SuggestionCallback callback) {
if(suggestBox.getText().length() > 1)
super.showSuggestions(suggestBox, suggestions, isDisplayStringHTML, isAutoSelectEnabled, callback);
}
}
public static class MySuggestion implements Suggestion {
private String text;
public MySuggestion(String text) {
this.text = text;
}
@Override
public String getDisplayString() {
return text;
}
@Override
public String getReplacementString() {
return text;
}
}
}