开发者

Android Development: Count EditText Lines on textChanged?

开发者 https://www.devze.com 2023-02-07 00:45 出处:网络
How can I count the number of lines in an EditText? Basically in my app I have line numbers and I wanted to make them update on textchange (I already have the textchangelistener set up).

How can I count the number of lines in an EditText? Basically in my app I have line numbers and I wanted to make them update on textchange (I already have the textchangelistener set up). Is this possible? :(

Th开发者_开发知识库anks, Alex!


Lines can be differents:

  • Visible lines: Wrapped text count as a new line...
  • List item: Only lines with \r, \n, \r\n

First case (the easiest):

int nbLines = editText.getLineCount();

Second case:

        int nbLines = 0;
        StringReader     sr = new StringReader(editText.getText().toString());
        LineNumberReader lnr = new LineNumberReader(sr);
        try { 
            while (lnr.readLine() != null){}
            nbLines = lnr.getLineNumber();
            lnr.close();
        } catch (IOException e) {
            nbLines = editText.getLineCount();
        } finally {
            sr.close();
        }


Depends on what you define as "line number". A line in your edittext in "GUI way", which includes the linebreaks your editview does? Or a line in a "coding way" of describing it (having \n at the end)? First one will be quite hard to get, if even impossible. Second one: just count the numbers of \n in the text, plus add another 1 if there is something after the last \n.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号