Android EditText 限制输入类型数字或小数,并且小数位数限定为两位


//允许输入数字并且可以为小数
edit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_VARIATION_NORMAL);
//contentEdit.setInputType(type);
contentEdit.addTextChangedListener(new TextWatcher() {
   private int selectionStart;
   private int selectionEnd;
   private CharSequence temp;

   @Override
   public void onTextChanged(CharSequence s, int start, int before, int count) {
      // TODO Auto-generated method stub
      temp = s;

   }
   
   @Override
   public void beforeTextChanged(CharSequence s, int start, int count, int after) {
      // TODO Auto-generated method stub
      
   }
   
   @Override
   public void afterTextChanged(Editable s) {
      // TODO Auto-generated method stub
      selectionStart = edit.getSelectionStart();
      selectionEnd = edit.getSelectionEnd();

      if (!StringUtil.isOnlyPointNumber(edit.getText().toString())){
         PromptManager.showToast(context,"您输入的数字保留在小数点后两位");
         //删除多余输入的字(不会显示出来)
         s.delete(selectionStart - 1, selectionEnd);
         edit.setText(s);
      }
      
   }

});
public static boolean isOnlyPointNumber(String number) {//保留两位小数正则
    Pattern pattern = Pattern.compile("^\\d+\\.?\\d{0,2}$");
    Matcher matcher = pattern.matcher(number);
    return matcher.matches();
}
xml布局文件   需加上
android:inputType="numberDecimal"

你可能感兴趣的:(Android EditText 限制输入类型数字或小数,并且小数位数限定为两位)