Using a regex pattern you can handle the numbers between -99.99
and 99.99
^[-+]?[0-9]{1,2}\.[0-9]{1,2}+$
Update 2:
For >=-100 and <=100, use this regex:
^[-+]100|^[-+]?[0-9]{1,2}.[0-9]{1,2}+$
Below sample, checks the text and enables/disables the button if matches or not.
EditText mEditText;
Button mButton;
final static String mRegex = "^[-+]100|^[-+]?[0-9]{1,2}\.[0-9]{1,2}+$";
boolean inputMatches;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = findViewById(R.id.editText);
mEditText.addTextChangedListener(new InputController());
mButton = findViewById(R.id.button);
mButton.setEnabled(inputMatches);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this," Input matches!", Toast.LENGTH_SHORT).show();
}
});
}
public class InputController implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
String input = mEditText.getText().toString();
inputMatches = input.matches(mRegex);
}
}
Update:
As per your request on clearing Edittext
.. There are multiple ways to do it. You can either follow other answers above or you can use my above answer if it fits with you and instead using TextWatches
, you can use OnFocusChangeListener
. This is better if you have multiple Edittexts. When your one Edittext
loses focus, then this code will trigger to see if it matches the regex pattern. If no match, clears it.
Remove above TextWatcher, follow bellow:
Implement OnFocusChangeListener
in your Activity
MainActivity extends AppCompatActivity implements View.OnFocusChangeListener
Override its onFocusChange
method.
@Override
public void onFocusChange(View view, boolean b) {}
Inside onFocusChange
do your checks.
@Override
public void onFocusChange(View view, boolean b) {
if(!b){ // Lost focus
String text = ((EditText)view).getText().toString();
if(text.matches(mRegex)){
// It matches
Toast.makeText(MainActivity.this, "Input matches!!!", Toast.LENGTH_SHORT).show();
}
else{
// No match - clear Edittext
((EditText)view).setText("");
Toast.makeText(MainActivity.this, "Input doesn't match", Toast.LENGTH_SHORT).show();
}
}
}
Update 2
To include -100 and 100, use this regex pattern:
^[-+]100|^[-+]?[0-9]{1,2}.[0-9]{1,2}+$