Pregunta

Tengo un texto de edición donde quiero ingresar un valor porcentual, es decir, un valor decimal, por lo que quiero limitar al usuario a ingresar solo un valor inferior a 100 en el texto de edición.

Ejemplo:1) si quiere entrar valor más de 100, él no debería permitirle para entrar en esto.

2)Si quiere entrar valor decimal inferior a 100, es decir, 50,5444 Entonces eso debería permitirle para ingresar este valor

yo también he encontrado este enlace donde puedo configurar el filtro para el valor entero máximo en 100 pero no me permite ingresar el valor decimal

enlace: http://tech.chitgoks.com/2011/06/27/android-set-min-max-value-an-edittext-accepts/

Alguien puede ayudarme.

¿Fue útil?

Solución

Oye, puedes usar el Vigilante de texto, aplícalo en tu EditText e implementar los tres métodos que proporciona.Luego, cuando inserta un nuevo valor, puede usar una expresión regular para verificar su validez.

¡Espero eso ayude!

Otros consejos

Aquí está el código de implementación completo que utilicé

editTextSpLinePercent.addTextChangedListener(new TextWatcher() {

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

    @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
        String enteredValue = s.toString();
        if(checkNullValues(enteredValue)) {
            if(Float.parseFloat(enteredValue.trim()) >100.0f){
                AlertDialog.Builder builder = new AlertDialog.Builder(SpecialDiscountLineActivity.this);
                // builder.setCancelable(true);
                builder.setMessage("Percentage Value should be Less than 100");

                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                         editTextSpLinePercent.setText("");
                    }
                });           
                builder.show();            
            }
        }
    }
});


public static boolean checkNullValues(String valueToCheck) {
    //Log.i("Log","CheckForNullValues : "+valueToCheck);
    if(!(valueToCheck == null)) {
        String valueCheck = valueToCheck.trim();
        if(valueCheck.equals("") || valueCheck.equals("0")  ) {
            //  Log.i("Log","Returning false 0 or Blank");
            return false;
        }
        return true;
    }
    //Log.i("Log","Returning false null");
    return false;
}

De hecho, puede modificar el útil fragmento de código proporcionado en el enlace mencionado en la pregunta de la siguiente manera.También, opcionalmente, puede incluir el número máximo de lugares decimales que desea que tenga el porcentaje y usar el comparador de patrones para devolver "" si la entrada no coincide con el patrón deseado.

private class PercentageInputFilter implements InputFilter {
    private float min;
    private float max;

    PercentageInputFilter(float min, float max) {
        this.min = min;
        this.max = max;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            // Get input
            String stringToMatch = dest.toString() + source.toString();
            float input = Float.parseFloat(stringToMatch);

            // Check if the input is in range.
            if (isInRange(min, max, input)) {
                // return null to accept the original replacement in case the format matches and text is in range.
                return null;
            }
        } catch (NumberFormatException nfe) {
        }
        return "";
    }

    private boolean isInRange(float min, float max, float input) {
        return input >= min && input <= max;
    }
}

Puedes usarlo como:

new PercentageInputFilter((float) 0.00, (float) 100.00);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top