I'm trying to do an IGV calculator, in Android Studio, with some additional features and I have several EditText. I need to change any of them, change the value of the others.
With the Textwatcher I achieve this but Unidirectionally. That is, if I have 3 EditTexts called: Subtotal, Igv and Total and the following is done: 1.- I write 100 in "Total", this causes that "subtotal" is equal to 84.75 and that "IGV" is 15.25. But if I fill "Subtotal" with 84.75 it hangs up because, I imagine, a vicious circle is created since "Subtotal" would modify "Total", but this in turn wants to modify the first one.
The code I am using is the following:
final EditText campoVentas = (EditText) findViewById(R.id.total_venta);
final EditText campoSubtotal = (EditText) findViewById(R.id.subtotal_venta);
final EditText campogananciaporc = (EditText) findViewById(R.id.ganancia_porc);
TextWatcher generalTextWatcher = new 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) {
if (campoVentas.getText().hashCode() == editable.hashCode()) {
Toast toast1 = Toast.makeText(getApplicationContext(),
"Campo Ventas", Toast.LENGTH_SHORT);
toast1.show();
if(null == editable || editable.length() == 0){
EditText subtotal = (EditText) findViewById(R.id.subtotal_venta);
EditText igv = (EditText) findViewById(R.id.igv_venta);
subtotal.setText("");
igv.setText("");
}
else {
EditText subtotal = (EditText) findViewById(R.id.subtotal_venta);
EditText igv = (EditText) findViewById(R.id.igv_venta);
Float num2 = Float.parseFloat(String.valueOf(editable));
double operacion = num2 / 1.18;
double resta = num2 - operacion;
String valor = String.valueOf(String.format("%.2f",operacion));
String valor2 = String.valueOf(String.format("%.2f",resta));
subtotal.setText(valor);
igv.setText(valor2);
}
} else if (campoSubtotal.getText().hashCode() == editable.hashCode()) {
Toast toast1 = Toast.makeText(getApplicationContext(),
"Campo subtotal", Toast.LENGTH_SHORT);
toast1.show();
if(null == editable || editable.length() == 0){
EditText total = (EditText) findViewById(R.id.total_venta);
EditText igv = (EditText) findViewById(R.id.igv_venta);
//total.setText("");
igv.setText("");
}
else {
EditText total = (EditText) findViewById(R.id.total_venta);
EditText igv = (EditText) findViewById(R.id.igv_venta);
final Float num2 = Float.parseFloat(String.valueOf(editable));
double operacion = num2 * 0.18;
double suma = num2 + operacion;
String valor = String.valueOf(String.format("%.2f",operacion));
String valor2 = String.valueOf(String.format("%.2f",suma));
igv.setText(valor);
//total.setText(valor2); //ES ACÁ DONDE FALLA
}
Let's see if they can give me a hand. Thank you very much.