Redrawing EditText after changing InputType

假装没事ソ 提交于 2021-02-08 07:57:20

问题


I have made a class that is responsible for monitoring an EditText widget following the Observer pattern. Its sole function is to disable or re-enable auto-correct based on a method call. I am able to successfully achieve this, but the problem is that the new InputType only applies to new text I add to the EditText - old text still retains the red underline to show that it can be auto-corrected.

Is there any way I can force the new InputType to apply to the entire EditText block, and not simply the new content I add? I tried calling editText.invalidate() and editText.refreshDrawableState() in the hope all the text would refresh, but to no avail.

final class SpellCheckerObserver implements EditTextObserver {

    public static final int KEY = KeyGenerator.generateUniqueId();

    private int defaultInputType;

    SpellCheckerObserver(EditTextSubject subject) {
        subject.attach(SpellCheckerObserver.KEY, this);
    }

    @Override
    public void activating(EditText editText) {

        defaultInputType = editText.getInputType();   
        editText.setRawInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

    }

    @Override
    public void deactivating(EditText editText) {
        editText.setInputType(defaultInputType);
    }

}

回答1:


I found out the answer whilst looking through the source code for TextView, where I came across the removeSuggestionSpans() method.I wasn't aware that the suggestions were in fact a type of span, (unsurprisingly, the SuggestionSpan)

This meant I was able to remove the red underline with the following code:

SuggestionSpan[] spans = editText.getText().getSpans(
        0, editText.length(), SuggestionSpan.class
);

if (spans.length > 0) {
    for (SuggestionSpan span : spans) {
        editText.getText().removeSpan(span);
    }
}


来源:https://stackoverflow.com/questions/34656907/redrawing-edittext-after-changing-inputtype

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