java—有没有一种方法可以在遇到字符串数组中的单词时更改edittext的文本颜色?

llew8vvj  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(325)

我正在尝试实现一些类似于代码编辑器的东西,其中关键字会自动高亮显示。我将有一个字符串数组,当用户键入文本并匹配字符串数组中的字符串时,我想更改edittext字符串的颜色和字体。我正在使用addtextchangelistener,但是整个edittext的文本发生了变化。我只想突出显示匹配的单词。这是我的密码:

inputCodeEditText.addTextChangedListener(new TextWatcher() {
        @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 (s.toString().contains("for"))
            {
                inputCodeEditText.setTextColor(getResources().getColor(R.color.indigo));
            }
        }
    });

I understand I have to use spans but the code crashes. Can anyone help me with the correct usage of spannable strings with addTextChangedListener() ?
fsi0uk1n

fsi0uk1n1#

使用addtextchangelistener api,例如:

editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // The changed text comes in "s" parameter.
                // Here you can watch the changes and take an action you want...
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

相关问题