set Decimal Edit Filter for EditText - Android User Interface

Android examples for User Interface:EditText

Description

set Decimal Edit Filter for EditText

Demo Code


//package com.java2s;
import android.text.InputFilter;
import android.text.Spanned;

import android.widget.EditText;

public class Main {
    public static void setDecimalEditFilter(EditText inputEdit,
            final int length) {
        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;
                }/* w ww.  j  av a 2  s. co  m*/
                String dValue = dest.toString();
                String[] splitArray = dValue.split("\\.");
                if (splitArray.length > 1) {
                    String dotValue = splitArray[1];
                    int diff = dotValue.length() + 1 - length;
                    if (diff > 0 && start >= 0 && start < source.length()
                            && end - diff >= 0
                            && end - diff < source.length()
                            && start <= end - diff) {
                        return source.subSequence(start, end - diff);
                    } else {
                        return null;
                    }
                }
                return null;
            }
        };
        inputEdit.setFilters(new InputFilter[] { lengthfilter });
    }
}

Related Tutorials