对此没有简单的解决方案。但是,我继续创建了一种几乎像双向绑定一样工作的更改。
我的 EditText 看起来像这样:
<EditText
android:id="@+id/amount"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.1"
android:digits="0123456789."
android:gravity="end"
android:inputType="numberDecimal|numberSigned"
android:onTextChanged="@{() -> handler.valueAmountChanged(amount)}"
android:selectAllOnFocus="true"
android:text="0"
android:textColor="@color/selector_disabled_edit_text"
app:userVal="@{userAmount}" />
handler 是活动的实例。它包含valueAmountChanged(EditText editText) 方法。
现在在您检查的值金额中,我正在解析该文本字符串并将其存储在相应的变量中。
对我来说,它看起来像这样:
public void valueAmountChanged(EditText editText) {
double d = 0.0;
try {
String currentString = editText.getText().toString();
// Remove the 2nd dot if present
if (currentString.indexOf(".", currentString.indexOf(".") + 1) > 0)
editText.getText().delete(editText.getSelectionStart() - 1, editText.getSelectionEnd());
// Remove extra character after 2 decimal places
currentString = editText.getText().toString(); // get updated string
if (currentString.matches(".*\\.[0-9]{3}")) {
editText.getText().delete(currentString.indexOf(".") + 3, editText.length());
}
d = Double.valueOf(editText.getText().toString());
} catch (NumberFormatException e) {
}
userAmount = d; // this variable is set for binding
}
现在,当我们更改 userAmount 变量时,它将反映我们在 EditText 中使用 app:userVal 参数设置绑定适配器。
因此,使用绑定适配器,我们检查新值是否不是当前值,然后更新该值。否则,保持原样。我们需要这样做,因为如果用户正在键入并且绑定适配器更新值,那么它会松开光标位置并将其带到前面。所以,这将使我们摆脱困境。
@BindingAdapter({"userVal"})
public static void setVal(EditText editText, double newVal) {
String currentValue = editText.getText().toString();
try {
if (Double.valueOf(currentValue) != newVal) {
DecimalFormat decimalFormat = new DecimalFormat("#.##");
String val = decimalFormat.format(newVal);
editText.setText(val);
}
} catch (NumberFormatException exception) {
// Do nothing
}
}
这有点典型,我知道。但是,找不到比这更好的了。可用的文档也非常少,其他的是以博客文章的形式出现在媒体上,应该已经添加到官方文档中。
希望对某人有所帮助。