android make automatic calculations from one edit text to another

0

I have been asked to make a program on android which is able to convert from Fahrenheit to celcius degrees and vice versa, up to here all easy, but, I wonder if it is possible to do that by putting 1 for example in Celcius degrees I present myself automatically its corresponding value in degrees Fahrenheit. Is there any way to do it?

This is my logical code for my application, which I need to give Enter to calculate the equivalence

public class MainActivity extends AppCompatActivity {

private EditText f,c;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    f = (EditText)findViewById(R.id.et_f);
    c = (EditText)findViewById(R.id.et_c);

    c.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            Double gf = ((1.8)*Double.parseDouble(c.getText().toString()))+32;
            f.setText(""+gf);

            return false;

        }

    });

    f.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            Double gc = (Double.parseDouble(f.getText().toString())-32)/1.8;
            c.setText(""+gc);

            return false;

        }

    });


}
}
    
asked by Barly Espinal 29.09.2018 в 01:52
source

1 answer

3

You should change the EditorActionListener to TextWatcher so you do not need to touch enter to run the calculation.

c.addTextChangedListener(new TextWatcher() {
   public void afterTextChanged(Editable s) {}
   public void beforeTextChanged(CharSequence s, int start,int count, int after) {}

   public void onTextChanged(CharSequence s, int start,int before, int count) {
      if(c.hasFocus()){
         try {
            Double gf = ((1.8)*Double.parseDouble(c.getText().toString()))+32;
            f.setText(""+gf);
         }
         catch(Exception e) {
            //Error de parseo 
         }
      }
   }
});

f.addTextChangedListener(new TextWatcher() {
   public void afterTextChanged(Editable s) {}
   public void beforeTextChanged(CharSequence s, int start,int count, int after) {}

   public void onTextChanged(CharSequence s, int start,int before, int count) {
      if(f.hasFocus()){
         try{
            Double gc = (Double.parseDouble(f.getText().toString())-32)/1.8;
            c.setText(""+gc);
         }
         catch(Exception e) {
            //Error de parseo 
         }
      }
   }
});

In addition, you add a validation with the hasFocus so that you only perform the calculation when the text changes by the input and not because it was modified by the change of the other EditText, preventing it from entering a loop.

    
answered by 29.09.2018 в 03:15