Reputation: 165
I've implemented an EditText for payments. Depending on the number I've entered, that amount is subtracted from the initial amount and displayed in the TextView above via TextWatcher Like this.
I'm using a TextWatcher to achieve this.
et_EnterInstallment.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
//To decrease the amount entered from the price (amount as displayed in textview)
String editTextValue = et_EnterInstallment.getText().toString();
if(!editTextValue.isEmpty()) {
int mainPrice = Integer.parseInt(price);
int enteredPrice = Integer.parseInt(et_EnterInstallment.getText().toString());
int valueAfterDeduction = mainPrice - enteredPrice;
tv_Price.setText(String.valueOf(valueAfterDeduction));
} else {
tv_Price.setText(price);
}
}
});
How can I validate the EditText values to achieve the following:
1) If the entered value is more than the price. In which case the user can't enter that number itself in the field (If Price is 3000, user has entered 350 and as he is about to enter another 0, the price will be greater, and hence he won't be able to enter that value in the EditText)
2) Disable the user from entering 0 or 00.
Upvotes: 1
Views: 327
Reputation:
This will validate your input as you go. By checking the input, as it is changed.
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(new String(s.toString()).equals("")){
// we don't want to try and parse an empty string to int or
// check for changes when the input is deleted.
}
else if(new String(s.toString()).equals("0")){
et_EnterInstallment.setText("");
Toast.makeText(context,"Do not enter an amount starting with 0",
Toast.LENGTH_LONG).show();
}
else if(Integer.parseInt(s.toString()) >3000){ // put price in there.
et_EnterInstallment.setText(s.toString().substring(0, s.toString().length() - 1));
et_EnterInstallment.setSelection(et_EnterInstallment.length());
Toast.makeText(context,"You cannot enter an installment " +
"greater than the total",
Toast.LENGTH_LONG).show();
}
}
Don't forget to only allow numeric input in your xml:
android:inputType="number"
I used a hardcoded value for price to test this.
A simple github sample.
Upvotes: 2