Android – Detect when user enters data into edittext immediately shows answer

androidandroid-emulatorandroid-layout

How is it possible to detect if a character is inputted into an EditText which makes it from 0 to 1 characters long and then perform some action?

Best Answer

Since you have a rather abstract question, let me attempt an equally generic answer:

In your onCreate(), declare and cast your EditText

EditText editText = (EditText) findViewById(R.id.editText);
editText.addTextChangedListener(filterTextWatcher);

And then, outside the onCreate(), setup the filterTextWatcher like this:

private TextWatcher filterTextWatcher = new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // DO THE CALCULATIONS HERE AND SHOW THE RESULT AS PER YOUR CALCULATIONS

        int radius = 0;
        radius = Integer.valueof(s.toString);
        double area = Math.PI * radius * radius;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
};

EDIT:

Updated code with possible calculation. (UNTESTED CODE: I JUST TYPED IT IN WITHOUT TESTING IT. MODIFY WHERE NECESSARY)

Read more about TextWatcher's here

And here are a few examples to get you started:

  1. http://www.android-ever.com/2012/06/android-edittext-textwatcher-example.html
  2. http://www.cybernetikz.com/blog/android-textwatcher-example/
  3. http://www.allappsdevelopers.com/TopicDetail.aspx?TopicID=22b00052-dad0-4e09-a07e-b74f115ab247
  4. http://myandroidsolutions.blogspot.in/2012/06/android-edittext-change-listener.html