1

How can I show the length of words typed into a textview?

This is the code, but my app stops responding if I type anything:

ed1=(EditText) findViewById(R.id.editText2);

ed1.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            TextView t1=(TextView) findViewById(R.id.textView1);
            t1.setText(ed1.getText().toString().length());
        }
    });

Code is written in onCreate().

1
  • you wan to show when you are typing ??? or after finishing typing Oct 24, 2015 at 15:34

2 Answers 2

2

Adding to @TanFang's answer , you need to cast the length to a string after getting it so the method will look like

@Override
public void afterTextChanged(Editable s) {
   // TODO Auto-generated method stub
   t1.setText(String.valueOf(s.length()));
}

Another thing is you should initialise your TextView outside the TextWatcher interface calls since they are called each time the content of your EditText changes and initialising views during that is going to cause performance issues

0
0

Try this.

    @Override
    public void afterTextChanged(Editable s) {
        TextView t1=(TextView) findViewById(R.id.textView1);
        t1.setText(s.length());
    }
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.