我正在尝试制作一个仅在输入 2 个字符后才显示建议的 SuggestBox。我的想法是在文本长度为 1 时隐藏建议,使用类 DefaultSuggestionDisplay。我试图在 SuggestionBox 本身及其 TextBox 上附加不同的处理程序,如 KeyPressHandler 和 KeyUpHandler,但它们似乎都不起作用。你有什么建议吗”?:D
问问题
961 次
2 回答
1
您可以扩展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;
}
}
}
于 2016-06-05T22:32:47.620 回答
0
您可以扩展 SuggestBox 并覆盖showSuggestionList()
方法。
添加 KeyUpHandler 不起作用,因为您添加了另一个 KeyUpHandler,而不是替换 SuggestBox 添加到其自己的 TextBox 中的那个。
编辑:
@Override
showSuggestionList() {
if (getTextBox().getValue().length() > 1) {
super.showSuggestionList();
}
}
于 2016-06-03T17:39:14.590 回答