问题
I want to get values of my textBox before change its value and after changed its value.
String beforeValue = "";
TextBox textBox = new TextBox();
textBox.addFocusHandler(new FocusHandler() {
public void onFocus(final FocusEvent event) {
beforeValue = textBox.getText();
}
});
textBox.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(final ValueChangeEvent<String> event) {
System.out.println("Before value is " + beforeValue);
System.out.println("After value is " + textBox.getText());
}
});
As above codes , I need two handlers (FocusHandler and ValueChangeHadler) to get before value and after value . My question is how can I get it by one Handler or another simple and easy way ? I don't want to use two handlers to get it. Any suggestions would be appreciated. Thanks in advance !
回答1:
Your idea(using 2 handlers) is fair enough but its buggy. I don't think it can be done in a better way. If you want to use a single handler, create a custom class wrapper using the two handlers.
Here is the code for you.
public abstract class MyValueChangeHandler<T> implements ValueChangeHandler<T> {
T prevValue = null;
T value = null;
public MyValueChangeHandler(final ValueBoxBase<T> widget) {
widget.addFocusHandler(new FocusHandler() {
public void onFocus(FocusEvent event) {
prevValue = widget.getValue();
}
});
}
@Override
public void onValueChange(ValueChangeEvent<T> event) {
value = event.getValue();
onValueChange(value, prevValue);
// or
// onValueChange(event, prevValue);
prevValue = value;
}
public abstract void onValueChange(T value, T prevValue);
// or
// public abstract void onValueChange(ValueChangeEvent<T> event, T prevValue);
}
And you can use it as,
TextBox box = new TextBox();
box.addValueChangeHandler(new MyValueChangeHandler<String>(box) {
@Override
public void onValueChange(String value, String prevValue) {
Window.alert("Prev Value : " + prevValue + " CurrnetValue: "
+ value);
}
});
来源:https://stackoverflow.com/questions/21347311/gwt-valuechangehandler-and-getting-before-value