自定义编辑文本Android

时间:2014-06-02 09:08:16

标签: android

我有2个android项目。 第一个项目 - >我使用自定义常规表达式自定义编辑文本

private static final String QUANTITY_REGEX = "^\\d{0,4}(\\,\\d{0,3})?$";

第二个项目 - >使用第一个项目中的自定义编辑文本的项目。

之后,我将第一个类导出为第二个项目的库作为自定义编辑文本。

问题是: 因为你可以在第一个项目上看到正则表达式,只允许首先写入4个数字,在编辑文本上的“,”符号后面加2个数字。但我想让自定义编辑文本像这样

重点:1234,56 !重点:1.234,56

如何使它成为可能。 THX

2 个答案:

答案 0 :(得分:0)

将正则表达式更改为^ \ d {0,4}(。\ d {0,4})?(,\ d {0,2})?$

private static final String QUANTITY_REGEX ="^\\d{0,4}(.\\d{0,4})?(,\\d{0,2})?$";

比赛将是

1234
1234.5678
1234.5678,12

答案 1 :(得分:0)

这里我弄清楚...希望对其他程序员有用

这个概念: 1编辑文字

当用户专注于edittext(txt1)时,用户只能在逗号​​(“,”)之后写入4个数字,逗号(“,”)和3个另一个数字 - >的 1234,567

当(txt1)onFocused = false(用户点击另一个editText)时,txt1会显示这样的数字 1.234,567

这里是代码

验证类

public class Validation {
// Regular Expression
// you can change the expression based on your need
private static final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final String PHONE_REGEX = "\\d{3}-\\d{7}";
private static final String CURRENCY_REGEX = "^\\d{0,8}(\\,\\d{0,2})?$";
public String maxLength = Quantity.maxLengthFront;
public String QUANTITY_REGEX = null;

// Error Messages
private static final String REQUIRED_MSG = "required";
private static final String EMAIL_MSG = "invalid email";
private static final String PHONE_MSG = "###-#######";
private static final String CURRENCY_MSG = "invalid currency";
private static final String QUANTITY_MSG = "invalid quantity";

// call this method when you need to check email validation
public static boolean isEmailAddress(EditText editText, boolean required) {
    return isValid(editText, EMAIL_REGEX, EMAIL_MSG, required);
}

// call this method when you need to check phone number validation
public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}

// call this method when you need to check currency validation
public static boolean isCurrency(EditText editText, boolean required) {
    return isValid(editText, CURRENCY_REGEX, CURRENCY_MSG, required);
}

public  boolean isQuantity(EditText editText, boolean required){
    return isValid(editText, QUANTITY_REGEX, QUANTITY_MSG, required);
}
// return true if the input field is valid, based on the parameter passed
public static boolean isValid(EditText editText, String regex, String errMsg, boolean required) {

    String text = editText.getText().toString().trim();
    // clearing the error, if it was previously set by some other values
    editText.setError(null);

    // text required and editText is blank, so return false
    if ( required && !hasText(editText) ) return false;

    // pattern doesn't match so returning false
    if (required && !Pattern.matches(regex, text)) {
        editText.setError(errMsg);
        return false;
    };

    // pattern doesn't match so returning false
    if (!required && !Pattern.matches(regex, text)) {
        editText.setError(errMsg);
        return false;
    };

    return true;
}

// check the input field has any text or not
// return true if it contains text otherwise false
public static boolean hasText(EditText editText) {

    String text = editText.getText().toString().trim();
    editText.setError(null);

    // length 0 means there is no text
    if (text.length() == 0) {
        editText.setError(REQUIRED_MSG);
        return false;
    }

    return true;
}
}

QUANTITY CLASS

public class Quantity extends EditText {
public static String maxLength;
public static String maxLengthFront = "4";
public static String regexCustom;
public boolean statusFocused = false;
public boolean allowBlank;
public String decimalPlaces;

String oldText;
Validation validation = new Validation();

public Quantity(Context context) {
    super(context);
}

public Quantity(Context context, AttributeSet attrs) {
    super(context, attrs);
    // --- Additional custom code --
    TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.Quantity);
    final int N = a.getIndexCount();
    for (int i = 0; i < N; ++i) {
        int attr = a.getIndex(i);
        switch (attr) {
        case R.styleable.Quantity_decimalPlaces_quantity:
            decimalPlaces = a.getString(attr);
            // ...do something with delimiter...
            break;
        case R.styleable.Quantity_maxLength_quantity:
            maxLength = "5";
            // ...do something with fancyText...
            doSetMaxLength();
            break;
        case R.styleable.Quantity_allowBlank_quantity:
            allowBlank = a.getBoolean(attr, false);
            // ...do something with fancyText...
            break;
        }
    }
    a.recycle();

    this.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
    this.setKeyListener(DigitsKeyListener.getInstance("1234567890-.,"));

    this.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            if (statusFocused == true) {
                maxLengthFront = "4";
                if (validation.isQuantity(Quantity.this, false)) {
                    // Toast.makeText(getContext(), "Validation True", Toast.LENGTH_SHORT).show();
                } else {
                    // Toast.makeText(getContext(), "Validation False",Toast.LENGTH_SHORT).show();
                    Quantity.this.setText(oldText);
                    Quantity.this.setSelection(Quantity.this.getText().length(), Quantity.this.getText().length());
                }
            } else {
                maxLengthFront = "5";
            }

            validation.QUANTITY_REGEX = "^\\d{0," + maxLengthFront + "}(\\,\\d{0,3})?$";

        }

        public void beforeTextChanged(CharSequence s, int start, int count,int after) {
            oldText = s.toString();
            // Toast.makeText(getContext(), "Before change : " + s, Toast.LENGTH_SHORT).show();
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    this.setOnFocusChangeListener(new OnFocusChangeListener() {
        public void onFocusChange(View v, boolean gainFocus) {
            // onFocus
            String s;
            if (gainFocus) {
                maxLengthFront = "4";
                validation.QUANTITY_REGEX = "^\\d{0," + maxLengthFront + "}(\\,\\d{0,3})?$";
                s = Quantity.this.getText().toString().replace(".", "");
                Quantity.this.setText(s);
                statusFocused = true;

            }

            // onBlur
            else {
                maxLengthFront = "5";
                validation.QUANTITY_REGEX = "^\\d{0," + maxLengthFront + "}(\\.\\d{0,3})?$";
                Double number = Double.parseDouble(Quantity.this.getText().toString());
                DecimalFormatSymbols symbol = DecimalFormatSymbols.getInstance();
                symbol.setGroupingSeparator('.');
                symbol.setDecimalSeparator(',');
                DecimalFormat formatter = new DecimalFormat("###,###.###", symbol);
                Quantity.this.setText(formatter.format(number));
                statusFocused = false;
            }
        }
    });
}

public Quantity(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    // --- Additional custom code --
}

// @Override
// protected void onTextChanged(CharSequence text, int start,
// int lengthBefore, int lengthAfter) {
// // TODO Auto-generated method stub
// super.onTextChanged(text, start, lengthBefore, lengthAfter);
// Toast.makeText(getContext(), this.getText() + " - " + text.toString(),
// Toast.LENGTH_SHORT).show();
// }

public void doSetMaxLength() {
    InputFilter[] FilterArray = new InputFilter[1];
    FilterArray[0] = new InputFilter.LengthFilter(Integer.parseInt(maxLength, 10));
    this.setFilters(FilterArray);
}
}