How to implement a simple Syntax highlighting method for edittext?

。_饼干妹妹 提交于 2019-12-06 01:47:55

问题


I am making an app that involves coding and I need edittext to recognize if the word typed was 'something' then depending if it is registered to be colored, it will color the word. Here is what I want to do, when the user is typing and types 'function' I want it to automatically highlight. Same goes to any other 'function' word, '()', ' " ', and many other words the user types.


回答1:


You can accomplish this by using a TextWatcher like so:

    editText.addTextChangedListener(new TextWatcher() {
        final String FUNCTION = "function";
        @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) {
            int index = s.toString().indexOf(FUNCTION);
            if (index >= 0) {
                s.setSpan(
                        new ForegroundColorSpan(Color.CYAN),
                        index,
                        index + FUNCTION.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    });


来源:https://stackoverflow.com/questions/20668792/how-to-implement-a-simple-syntax-highlighting-method-for-edittext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!