每次插入新行后Android都会获得EditText行数

时间:2017-05-30 08:26:25

标签: android

通过以下代码我试图在插入新行后显示EditText行数,此代码仅适用于第一个新行,之后,对于每个类型字符EditText我得到在LogCat

上插入新行日志
editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    @Override
    public void onTextChanged(CharSequence text, int start, int before, int count) {
        if (-1 != text.toString().indexOf("\n")) {
            Log.e("new line ", "enter new line" + "");
        }
    }
    @Override
    public void afterTextChanged(Editable s) {
    }
});

2 个答案:

答案 0 :(得分:1)

你必须计算换行符:

int counter = 0;

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    @Override
    public void onTextChanged(CharSequence text, int start, int before, int count) {
        if(before==0) {
            counter = 0;
            for (int i = 0; i < text.toString().length(); i++) {
                if (text.toString().charAt(i) == '\n') {
                    counter++;
                }
            }
        }
        Log.e("total new line ", "counter: " + counter);
    }
    @Override
    public void afterTextChanged(Editable s) {
    }
});

答案 1 :(得分:0)

试试这个。

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    @Override
    public void onTextChanged(CharSequence text, int start, int before, int count) {
        String insertedString =  text.toString();
        if (text.length() > 0 && insertedString.substring(insertedString.length() - 1).equals("\n")) {
             Log.e("new line ", "enter new line " + (channelMessageBox.getLineCount() - 1));
        }
    }
    @Override
    public void afterTextChanged(Editable s) {
    }
});