繁体   English   中英

如何检查是否在编辑文本中添加或删除了新行?

[英]How to check if a new line is added or removed in a Edit Text?

我有一个编辑文本。 我很容易就能从关键事件中得到新的一行。 但是,如果文本超出并转到下一行怎么办。 还有当用户按下退格键时,如何知道一行何时被删除? 我怎样才能在编辑文本中获得所有这些动作? 实际上,我想在添加或删除新行时将 animation 添加到具有扩展和收缩 animation 的编辑文本中。 也欢迎任何替代答案。

提前致谢。

您可以使用 TextWatcher 来监听 EditText 中的行数。

Kotlin

binding.notes.addTextChangedListener(object :TextWatcher{
        var linesCount = 0
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable?) {
            if(linesCount< binding.notes.lineCount){
                Log.d("HomeFragment", "afterTextChanged: New line")

            }else if( linesCount > binding.notes.lineCount){
                Log.d("HomeFragment", "afterTextChanged: Line removed")

            }
            linesCount = binding.notes.lineCount
        }

    })

Java

EditText notes = findViewById(R.id.notes);
    notes.addTextChangedListener(new TextWatcher() {
        int linesCount = 0;
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(linesCount< notes.getLineCount()){
                Log.d("HomeFragment", "afterTextChanged: New line");

            }else if( linesCount > notes.getLineCount()){
                Log.d("HomeFragment", "afterTextChanged: Line removed");

            }
            linesCount = notes.getLineCount();
        }
    });

其中notes是 EditText id。

editText 中的文本发生变化后,您可以查看添加字符后更改的行数。

到目前为止,这对您有帮助,但还可以改进。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM