2

我想以编程方式启用或禁用 EditText 中的自动大写、自动更正或密码字段(显示项目符号)。这意味着不是来自 XML

我也想避免TextWatcher解决方案,而更多地关注InputFilter或其他一些解决方案。

将 EditText 操作为 Editable 允许附加 InputFilters,但是我无法让这些以编程方式工作。此外,诸如setAllCaps 之类的 EditText 方法在实践中对我没有任何作用。自动校正也是如此。这是我尝试的自动更正(向您展示我在哪里,以及我的一些思考过程):

/** SpellCheck filter for auto-correcting words. */
class SpellCheckFilter implements InputFilter {

    public String word;

    public SpellCheckFilter()
    {
        word = " ";
    }

    //FIXME not returning corrected word. Try adjusting start/end values,
    //what range does this return?
    @Override
    public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {
        word += source;
        Log.i("SpellCheckFilter", "source=\"" + source + "\";  word=\"" + word + "\"");
        if (source.toString().endsWith(" "))
        {
            word = word.replace(" ", "");
            String correction = AutoText.get(word, 0, word.length()-1, view);
            Log.i("TextEditor", "Corrected word=" + (correction == null ? word : correction));
            word = " ";
            return correction;
        }
        return null;
    }

}

使用InputFilter.AllCaps,我能够获得一个几乎可以正常工作的自动大写方法,但是第一个字母没有自动大写。

4

1 回答 1

0
    //Calling Method
    setListener1(editText);
    //Method
    public void setListener1(final AppCompatEditText edittext) {
            final TextWatcher textWatcher = 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) {
                    String input = StringStaticMethods.firstCapital(s.toString());
                    edittext.removeTextChangedListener(this);
                    edittext.setText("");
                    edittext.append(input);
                    edittext.addTextChangedListener(this);
                }
            };
            edittext.addTextChangedListener(textWatcher);
        }
public static String firstCapital(String str) {
        if (str != null && !str.equals("")) {
            return (str.substring(0, 1).toUpperCase() + str.substring(1, str.length()));
        }
        return "";
    }
    //Use in XML
    android:inputType="textFilter|textMultiLine|textNoSuggestions"
于 2019-01-01T11:03:38.170 回答