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

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

将EditText操纵为Editable可以附加InputFilter,但是我无法以编程方式使它们工作。另外,诸如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,我可以获得几乎可以使用的自动大写方法,但是第一个字母没有自动大写。

最佳答案

    //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"

10-08 02:57