gpt4 book ai didi

java - 如何修复android中编辑文本的 double 值的最小值和最大值?

转载 作者:行者123 更新时间:2023-12-01 06:16:48 33 4
gpt4 key购买 nike

我已经提到了这个link

设置允许输入的编辑文本的最小值和最大值。但我想将最小值和最大值固定为双值。最小值应允许从 0.25 开始输入,最大值应允许输入 1000.0。如何解决?

最佳答案

您可以使用输入过滤器。这是我的解决方案

public class MinMaxInputFilter implements InputFilter {
private double mMinValue;
private double mMaxValue;

private static final double MIN_VALUE_DEFAULT = Double.MIN_VALUE;
private static final double MAX_VALUE_DEFAULT = Double.MAX_VALUE;

public MinMaxInputFilter(Double min, Double max) {
this.mMinValue = (min != null ? min : MIN_VALUE_DEFAULT);
this.mMaxValue = (max != null ? max : MAX_VALUE_DEFAULT);
}

public MinMaxInputFilter(Integer min, Integer max) {
this.mMinValue = (min != null ? min : MIN_VALUE_DEFAULT);
this.mMaxValue = (max != null ? max : MAX_VALUE_DEFAULT);
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
String replacement = source.subSequence(start, end).toString();
String newVal = dest.subSequence(0, dstart).toString() + replacement
+ dest.subSequence(dend, dest.length()).toString();

// check if there are leading zeros
if (newVal.matches("0\\d+.*"))
if (TextUtils.isEmpty(source))
return dest.subSequence(dstart, dend);
else
return "";

// check range
double input = Double.parseDouble(newVal);
if (!isInRange(mMinValue, mMaxValue, input))
if (TextUtils.isEmpty(source))
return dest.subSequence(dstart, dend);
else
return "";

return null;
} catch (NumberFormatException nfe) {
LOGE("inputfilter", "parse");
}
return "";
}

private boolean isInRange(double a, double b, double c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}

如何使用:

   editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

InputFilter limitFilter = new MinMaxInputFilter(mMinValue, mMaxValue);
editText.setFilters(new InputFilter[] { limitFilter });

关于java - 如何修复android中编辑文本的 double 值的最小值和最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22708070/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com