Search code examples
androidtextwatcher

Android TextView TextWatcher


So I have two EditText and one TextView, the two EditText is in Number format, I use it to compare the two which is greater or less than... and for the TextView this is where I put the output. My question is, when I input the numbers in edit text, there is no changes in Textview.

below is my code:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    etnumb_one= findViewById(R.id.etnumb_one);
    etnumb_two= findViewById(R.id.etnumb_two);
    tvOutput= findViewById(R.id.tvOutput);

    tvOutput.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)
        {
            tvOutput.setText(getOutput());
        }
    });
}

below is my method outside the onCreate

 public String getOutput()
{
    int first = Integer.parseInt(etnumb_one.getText().toString());
    int second= Integer.parseInt(etnumb_two.getText().toString());

    String output;

    if(first > second)
    {
        output= Integer.toString(first) + " : " + Integer.toString(second);
    }
    else
    {
        output= Integer.toString(first) + " : " + Integer.toString(second);
    }
    return output;
}

I just want to view the output in the textview. thank you!


Solution

  • You are adding TextWatcher on TextView and not on EditText.

    Instead of

    tvOutput.addTextChangedListener
    

    Use:

    etnumb_one.addTextChangedListener