android 开发中遇到的关于edittext输入类型为数字时如何在xml中编辑可输入的固定的小数位数,对于此问题本人解决方案如下
一、新建NumberEditText 继承 EditText 具体如下
/**
-
@author:Mr.Zan
-
@date: 2020/10/16 17:44
-
email:644962006@qq.com
-
detail:数字输入,并限制小数点后位数
*/
@SuppressLint(“AppCompatCustomView”)
public class NumberEditText extends EditText {
private int maxDecimalPoint = 2;
private boolean isFocus = false;public NumberEditText(Context context) {
super(context);
// TODO Auto-generated constructor stub
}public NumberEditText(Context context, AttributeSet attrs) {
super(context, attrs);
changeText(context, attrs);
setTextWatcher();
setFocusChange();
}public void changeText(Context context, AttributeSet attrs) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.NumberEditText); maxDecimalPoint = array.getInt(R.styleable.NumberEditText_maxDecimalPoint, 2); array.recycle();
}
public void setTextWatcher() {
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (isFocus) { String s1 = s.toString().trim(); if (s1.length() > 1 && s1.startsWith("0")) { String s2 = s1.substring(1); setText(s2); setSelection(s2.length()); } if (start >= 0) {//从一输入就开始判断, try { if (s1.startsWith(".")) { setText("0."); setSelection(s.length() + 1); } else if (s1.contains(".") && (s1.length() - s1.indexOf(".") > (maxDecimalPoint + 1))) { setText(s1.substring(0, s.length() - 1)); setSelection(s.length() - 1); } } catch (Exception e) { e.printStackTrace(); } return; } } } @Override public void afterTextChanged(Editable s) { } });
}
/**
*监听失去焦点时格式化数字使结尾不为0 或者小数点
*/
public void setFocusChange() {
setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
isFocus = hasFocus;
if (!hasFocus) {
String trim = getText().toString().trim();
if (!TextUtils.isEmpty(trim)) {
double v1 = Double.parseDouble(trim);
DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
String format = decimalFormat.format(v1);
setText(format);
}} } });
}
二、在res 下的velues 文件夹下添加 attrs.xml
在该文件中添加如下代码
-
<declare-styleable name="NumberEditText"> <attr name="maxDecimalPoint" format="integer" /> </declare-styleable>
三、使用方法
- 在布局文件中添加 <com.*****.NumberEditText
- 设置输入类型 android:inputType=“numberDecimal”
- 默认保留2位小数 需要修改为其他的位数只需添加 app:maxDecimalPoint=“n” 需要保留几位小数 n输入几就可以了