先看下XML布局文件
- <EditText
- android:id="@+id/et"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_toLeftOf="@+id/tv_count"
- android:background="@null"
- android:hint="@string/free_txt"
- android:inputType="numberDecimal"
- android:maxLength="10"
- android:singleLine="true"
- android:textColor="@color/txt_black1"
- android:textColorHint="@color/txt_gray2"
- android:textSize="@dimen/textsize16" />
- android:inputType="numberDecimal"
这句的属性是可输入小数
- /** 输入框小数的位数*/
- private static final int DECIMAL_DIGITS = 1;
- /**
- * 设置小数位数控制
- */
- InputFilter lengthfilter = new InputFilter() {
- public CharSequence filter(CharSequence source, int start, int end,
- Spanned dest, int dstart, int dend) {
- // 删除等特殊字符,直接返回
- if ("".equals(source.toString())) {
- return null;
- }
- String dValue = dest.toString();
- String[] splitArray = dValue.split("\\.");
- if (splitArray.length > 1) {
- String dotValue = splitArray[1];
- int diff = dotValue.length() + 1 - DECIMAL_DIGITS;
- if (diff > 0) {
- return source.subSequence(start, end - diff);
- }
- }
- return null;
- }
- };
- mEt.addTextChangedListener(mTextWatcher);
- mEt.setFilters(new InputFilter[] { lengthfilter });
这样就OK了,很简单吧,其实这个InputFilter很强大滴
//-------------------------------------------------------------------------
注意:split("\\.")这里需要转义。