Search code examples
androidandroid-layoutandroid-edittextandroid-textwatcher

How Android EditText inputType attribute with value textMultiLine breaks the lines?


I have an EditText field with the attribute inputType set to textMultiLine, this breaks a text into several lines, so far so good. I attached a TextWatcher to the EditText so I can check for any change. In the method afterTextChanged I want to check when a line of text is broken into 2 lines, but the textMultiLine attribute does not add a new line char, so my question is:

How can I check how many lines of text have been written in an EditText with the inputType attribute set to textMultiLine if there is not new line character?


Solution

  • No need to use a Runnable or post to a message queue. Simply call EditText.getLineCount() in your afterTextChanged() method:

    final EditText editText = /* your EditText here */;
    editText.addTextChangedListener(new TextWatcher() {
        ...
        @Override
        public void afterTextChanged(Editable editable) {
            int numLines = editText.getLineCount();
            // your code here
        }
    });