如何在android中设置两个整数后的小数点,并将限制设置为仅55位?经过大量搜索,我在这里发布了我的问题。我有Edittext
android:inputType="number"
。我可以将最大限制设置为EditText
到55位。我希望用户能够键入小数位,在0到55之间数字,如24.22或52.88。
有些人可以告诉我如何实现这一目标? 这是我的代码。
public class FuelCostCalculator extends DialogFragment {
EditText etLocation, etKilo, etLiter, etFuelCost;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, R.style.fullscreen_dialog);
}
private void init(View view) {
//this is my editText
etLiter = view.findViewById(R.id.etLiter);
InputFilterMinMax filter = new InputFilterMinMax("0", "5499") {};
etLiter.setFilters(new InputFilter[]{filter});
}
}
我的过滤器类是:
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
感谢任何形式的帮助:
答案 0 :(得分:-1)
检查这个答案。虽然它不是那么干净但它可以根据您的需要工作。假设actAddItemFromDropdownList是您的编辑文本,并且您已在Xml中设置了最大数字限制。
int max =0;
String text ="";
actAddItemFromDropdownList.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if(actAddItemFromDropdownList.getText().length()>0){
if(text.equals(actAddItemFromDropdownList.getText().toString())){
text = "";
}else {
text = actAddItemFromDropdownList.getText().toString();
max = max + 1;
if (max == 2) {
text = text + ".";
max = 0;
actAddItemFromDropdownList.setText(text);
actAddItemFromDropdownList.setSelection(actAddItemFromDropdownList.getText().length());
}
}
}
}
});
尝试它,如果它工作标记为选定的答案。