Search code examples
javaandroidandroid-edittext

Writing inside EditText


I have two EdiText and when I write a number in the first one I would need the second to be set to 162 - first one. If it is necessary to re-type a second number, the component should recalculate the first number.

If I write something in the second the first must behave exactly like the second.

Below there is my code but it does not work:

    inputScoreWe = findViewById(R.id.inputScoreWe);
    inputScoreYou = findViewById(R.id.inputScoreYou);

    View.OnClickListener inputScoreListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {

                int inputScoreWeInteger = Integer.parseInt(inputScoreWe.getText().toString());
                int inputScoreYouInteger = Integer.parseInt(inputScoreYou.getText().toString());

                if (inputScoreWeInteger > 0) {
                    inputScoreYouInteger = 162 - inputScoreWeInteger;
                } else if (inputScoreYouInteger > 0) {
                    inputScoreWeInteger = 162 - inputScoreYouInteger;
                }

                String s1 = inputScoreWeInteger + "";
                String s2 = inputScoreYouInteger + "";

                inputScoreWe.setText(s1);
                inputScoreYou.setText(s2);

            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();

            }
        }
    };

    inputScoreWe.setOnClickListener(inputScoreListener);
    inputScoreYou.setOnClickListener(inputScoreListener);

Solution

  • Use text change listener to trigger for everytime you change value

     inputScoreWe.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) {
                       if(s.length() > 0){
                          inputScoreYou.setText(162 - Integer.parseInt(inputScoreYou.getText().toString())+"");
                       }
    
                    }
    
                    @Override
                    public void afterTextChanged(Editable s) {
    
                    }
                });