import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.DigitsKeyListener;
public class MoneyValueFilter extends DigitsKeyListener {
public MoneyValueFilter() {
super(false, true);
}
private int digits = 2;
public void setDigits(int d) {
digits = d;
}
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
CharSequence out = super.filter(source, start, end, dest, dstart, dend);
// if changed, replace the source
if (out != null) {
source = out;
start = 0;
end = out.length();
}
int len = end - start;
// if deleting, source is empty
// and deleting can't break anything
if (len == 0) {
return source;
}
int dlen = dest.length();
// Find the position of the decimal .
for (int i = 0; i < dstart; i++) {
if (dest.charAt(i) == '.') {
// being here means, that a number has
// been inserted after the dot
// check if the amount of digits is right
return (dlen-(i+1) + len > digits) ?
"" :
new SpannableStringBuilder(source, start, end);
}
}
for (int i = start; i < end; ++i) {
if (source.charAt(i) == '.') {
// being here means, dot has been inserted
// check if the amount of digits is right
if ((dlen-dend) + (end-(i + 1)) > digits)
return "";
else
break; // return new SpannableStringBuilder(source, start, end);
}
}
// if the dot is after the inserted part,
// nothing can break
return new SpannableStringBuilder(source, start, end);
}
}
import android.text.InputFilter;
import android.text.Spanned;
/**
* Input filter that limits the number of decimal digits that are allowed to be
* entered.
*/
public class DecimalDigitsInputFilter implements InputFilter {
private final int decimalDigits;
/**
* Constructor.
*
* @param decimalDigits maximum decimal digits
*/
public DecimalDigitsInputFilter(int decimalDigits) {
this.decimalDigits = decimalDigits;
}
@Override
public CharSequence filter(CharSequence source,
int start,
int end,
Spanned dest,
int dstart,
int dend) {
int dotPos = -1;
int len = dest.length();
for (int i = 0; i < len; i++) {
char c = dest.charAt(i);
if (c == '.' || c == ',') {
dotPos = i;
break;
}
}
if (dotPos >= 0) {
// protects against many dots
if (source.equals(".") || source.equals(","))
{
return "";
}
// if the text is entered before the dot
if (dend <= dotPos) {
return null;
}
if (len - dotPos > decimalDigits) {
return "";
}
}
return null;
}
}
yourEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
NumberFormat formatter = new DecimalFormat("#.##");
double doubleVal = Double.parseDouble(s.toString());
yourEditText.setText(formatter.format(doubleVal));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
@Override
public void afterTextChanged(Editable s) {}
});
final EditText et = (EditText) findViewById(R.id.EditText1);
int count = -1;
et.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
if (arg0.length() > 0) {
String str = et.getText().toString();
et.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
count--;
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(100);
et.setFilters(fArray);
//change the edittext's maximum length to 100.
//If we didn't change this the edittext's maximum length will
//be number of digits we previously entered.
}
return false;
}
});
char t = str.charAt(arg0.length() - 1);
if (t == '.') {
count = 0;
}
if (count >= 0) {
if (count == 2) {
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(arg0.length());
et.setFilters(fArray);
//prevent the edittext from accessing digits
//by setting maximum length as total number of digits we typed till now.
}
count++;
}
}
}
});
CurrencyFormat watcher = new CurrencyFormat();
priceEditText.addTextChangedListener(watcher);
班级:
public static class CurrencyFormat implements TextWatcher {
public void onTextChanged(CharSequence arg0, int start, int arg2,int arg3) {}
public void beforeTextChanged(CharSequence arg0, int start,int arg2, int arg3) {}
public void afterTextChanged(Editable arg0) {
int length = arg0.length();
if(length>0){
if(nrOfDecimal(arg0.toString())>2)
arg0.delete(length-1, length);
}
}
private int nrOfDecimal(String nr){
int len = nr.length();
int pos = len;
for(int i=0 ; i<len; i++){
if(nr.charAt(i)=='.'){
pos=i+1;
break;
}
}
return len-pos;
}
}
EditText targetEditText = (EditText)findViewById(R.id.targetEditTextLayoutId);
targetEditText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
public void afterTextChanged(Editable arg0) {
String str = targetEditText.getText().toString();
if (str.isEmpty()) return;
String str2 = PerfectDecimal(str, 3, 2);
if (!str2.equals(str)) {
targetEditText.setText(str2);
targetEditText.setSelection(str2.length());
}
}
});
包括以下功能:
public String PerfectDecimal(String str, int MAX_BEFORE_POINT, int MAX_DECIMAL){
if(str.charAt(0) == '.') str = "0"+str;
int max = str.length();
String rFinal = "";
boolean after = false;
int i = 0, up = 0, decimal = 0; char t;
while(i < max){
t = str.charAt(i);
if(t != '.' && after == false){
up++;
if(up > MAX_BEFORE_POINT) return rFinal;
}else if(t == '.'){
after = true;
}else{
decimal++;
if(decimal > MAX_DECIMAL)
return rFinal;
}
rFinal = rFinal + t;
i++;
}return rFinal;
}
InputFilter filter = new InputFilter() {
final int maxDigitsBeforeDecimalPoint=4;
final int maxDigitsAfterDecimalPoint=1;
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dstart, dend, source
.subSequence(start, end).toString());
if (!builder.toString().matches(
"(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"
)) {
if(source.length()==0)
return dest.subSequence(dstart, dend);
return "";
}
return null;
}
};
mEdittext.setFilters(new InputFilter[] { filter });
import android.text.InputFilter;
import android.text.Spanned;
public class DecimalDigitsInputFilterNew implements InputFilter {
private final int decimalDigits;
private final int before;
public DecimalDigitsInputFilterNew(int before ,int decimalDigits) {
this.decimalDigits = decimalDigits;
this.before = before;
}
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dstart, dend, source
.subSequence(start, end).toString());
if (!builder.toString().matches("(([0-9]{1})([0-9]{0,"+(before-1)+"})?)?(\\.[0-9]{0,"+decimalDigits+"})?")) {
if(source.length()==0)
return dest.subSequence(dstart, dend);
return "";
}
return null;
}
}
public class DecimalDigitsInputFilter implements InputFilter {
Pattern mPattern;
public DecimalDigitsInputFilter() {
mPattern = Pattern.compile("[0-9]*+((\\.[0-9]?)?)||(\\.)?");
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Matcher matcher = mPattern.matcher(dest);
if (!matcher.matches())
return "";
return null;
}
}
et.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
String text = arg0.toString();
if (text.contains(".") && text.substring(text.indexOf(".") + 1).length() > 2) {
et.setText(text.substring(0, text.length() - 1));
et.setSelection(et.getText().length());
}
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
}
});
public class DecimalDigitsInputFilter implements InputFilter
{
Pattern pattern;
public DecimalDigitsInputFilter(int digitsBeforeDecimal, int digitsAfterDecimal)
{
pattern = Pattern.compile("(([1-9]{1}[0-9]{0," + (digitsBeforeDecimal - 1) + "})?||[0]{1})((\\.[0-9]{0," + digitsAfterDecimal + "})?)||(\\.)?");
}
@Override public CharSequence filter(CharSequence source, int sourceStart, int sourceEnd, Spanned destination, int destinationStart, int destinationEnd)
{
// Remove the string out of destination that is to be replaced.
String newString = destination.toString().substring(0, destinationStart) + destination.toString().substring(destinationEnd, destination.toString().length());
// Add the new string in.
newString = newString.substring(0, destinationStart) + source.toString() + newString.substring(destinationStart, newString.length());
// Now check if the new string is valid.
Matcher matcher = pattern.matcher(newString);
if(matcher.matches())
{
// Returning null indicates that the input is valid.
return null;
}
// Returning the empty string indicates the input is invalid.
return "";
}
}
// To use this InputFilter, attach it to your EditText like so:
final EditText editText = (EditText) findViewById(R.id.editText);
EditText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(4, 4)});
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
String numero = total.getText().toString();
int dec = numero.indexOf(".");
int longitud = numero.length();
if (dec+3 == longitud && dec != -1) { //3 number decimal + 1
log.i("ento","si");
numero = numero.substring(0,dec+3);
if (contador == 0) {
contador = 1;
total.setText(numero);
total.setSelection(numero.length());
} else {
contador = 0;
}
}
}
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.DigitsKeyListener;
public class MoneyValueFilter extends DigitsKeyListener {
public MoneyValueFilter() {
super(false, true);
}
private int digits = 2;
public void setDigits(int d) {
digits = d;
}
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
CharSequence out = super.filter(source, start, end, dest, dstart, dend);
// if changed, replace the source
if (out != null) {
source = out;
start = 0;
end = out.length();
}
int len = end - start;
// if deleting, source is empty
// and deleting can't break anything
if (len == 0) {
return source;
}
int dlen = dest.length();
// Find the position of the decimal .
for (int i = 0; i < dstart; i++) {
if (dest.charAt(i) == '.') {
// being here means, that a number has
// been inserted after the dot
// check if the amount of digits is right
return (dlen-(i+1) + len > digits) ?
"" :
new SpannableStringBuilder(source, start, end);
}
}
for (int i = start; i < end; ++i) {
if (source.charAt(i) == '.') {
// being here means, dot has been inserted
// check if the amount of digits is right
if ((dlen-dend) + (end-(i + 1)) > digits)
return "";
else
break; // return new SpannableStringBuilder(source, start, end);
}
}
// if the dot is after the inserted part,
// nothing can break
return new SpannableStringBuilder(source, start, end);
}
}
class PropertyCostInputFilter : DigitsKeyListener(false, true) {
override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence {
var source = source
var start = start
var end = end
val out = super.filter(source, start, end, dest, dstart, dend)
if (out != null) {
source = out
start = 0
end = out.length
}
val sourceLength = end - start
// If length = 0, then there was a deletion and therefore the length could not become greater than the max value
if (sourceLength == 0) {
return source
}
val result = dest.replaceRange((dstart until dend), source.substring(start, end))
val parts = result.split(SEPARATOR)
if (parts.size > 0 && parts[0].length > INTEGER_PART_MAX_DIGITS
|| parts.size > 1 && parts[1].length > FRACTIONAL_PART_MAX_DIGITS
) {
return ""
}
return SpannableStringBuilder(source, start, end)
}
companion object {
private const val INTEGER_PART_MAX_DIGITS = 20
private const val FRACTIONAL_PART_MAX_DIGITS = 2
private const val SEPARATOR = '.'
}
}