Como definir filtro de entrada para texto de edição no Android para decimal
-
27-10-2019 - |
Pergunta
Eu tenho o texto de edição em que desejo inserir o valor percentual, ou seja, o valor decimais. Portanto, quero limitar o usuário a inserir apenas valores inferiores a 100 no texto de edição.
Exemplo: 1) se ele deseja inserir valor maior que 100 , não deve permitir que insira isso.
2) Se ele quiser que t0 insira valor decimal menor que 100, ou seja, 50,5444 , então deve permitir que ele insira esse valor
Também encontrei este link onde posso definir o filtro para o valor inteiro máximo para 100, mas não me permite inserir o valor decimal
link: http://tech.chitgoks.com/2011/06/27/android-set-min-max-value-an-edittext-accepts/
Alguém pode me ajudar.
Solução
Ei, você pode usar o TextWatcher , aplicá-lo ao seu EditText
e implementar os três métodos fornecidos.Então, ao inserir um novo valor, você pode usar um RegEx para verificar sua validade.
Espero que ajude!
Outras dicas
Aqui está o código de implementação completo que usei
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;
}
Você pode modificar o trecho de código útil fornecido no link mencionado na pergunta da seguinte maneira.Também opcionalmente, você pode incluir o número máximo de casas decimais que deseja que a porcentagem tenha e usar o combinador de padrões para retornar ""
se a entrada não corresponder ao padrão pretendido.
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;
}
}
Você pode usá-lo como:
new PercentageInputFilter((float) 0.00, (float) 100.00);