Search code examples
androidtextwatcher

runtime TextWatcher control


I have 4 edittext and i would like to implement a TextWatcher with a control value.

Et1Burro.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable value) {
              // you can call or do what you want with your EditText here
                Dvalue = GetEditValue(value);
                double et4tot = 0, et2fibra = 0, et3zucc = 0;
                // et1burro + et2fibra = et4tot
                // et1burro + et2fibra + et3zucc = 100
                try {
                    et4tot = Double.parseDouble(Et4Tot.getText().toString());
                } catch (NumberFormatException e) { e.printStackTrace(); }

                try {
                    et2fibra = Double.parseDouble(Et2Fibra.getText().toString()); 
                } catch (NumberFormatException e) { e.printStackTrace(); }

                try {   
                    et3zucc = Double.parseDouble(Et3Zucc.getText().toString());
                } catch (NumberFormatException e) { e.printStackTrace(); }

                if ((Dvalue < 1) || (Dvalue > 100) || ((Dvalue + et2fibra) != et4tot ) || ((Dvalue + et2fibra + et3zucc) != 100 ))
                {
                //segnala errore
                    Et1Burro.setTextColor(getActivity().getBaseContext().getResources().getColor(R.color.Red)); 
                }else
                    Et1Burro.setTextColor(getActivity().getBaseContext().getResources().getColor(R.color.Black));
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
         });    

i would like to have a red number if the range number is wrong and a black number if is correct.

I think is better to implement a AsynckTask for control the number or not?

for example the 4 edittext value are: A,B,C,D

the relation for correct value are:

A+B = D
A+B+C = 100
C = 100 - D

correct example value are A=35, B=35, C=30, D=70 but if in teh first edit (A) the user insert the first caracter ex 35 the program respond with RED value because the other value are 0, and when the user compile all the edittext with the value 35,35,30,70 the anly value that are Black is the last. I hope to be clear...


Solution

  • Because you are updating only one edit text's color

    What i would suggest is,

    • Set default color to RED for all edit texts
    • Write a function for your "control value" logic. Call this function only when there are values in all edit texts.
    • Update all the editbox's color to black if the values entered are passing your control logic. Else you have to set it to RED