2

我正在尝试以编程方式设置“首字母大写” (因为我已经设置了EditTextin ListView

与这个问题相关的话题很多,其中最著名的是猜。我已经尝试过那里提供的解决方案,并且

setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)

真的很有帮助。例外 - 当用户使用GBoard (谷歌键盘)时它没有帮助。(自动大写没有关闭)

那么,是否有可能使其工作GBoard?或者也许......press shift当没有文本时是否可以进行程序化edittext

4

1 回答 1

1

我在 Gboard 上遇到了同样的问题并以这种方式解决了它:

final EditText editText = (EditText) findViewById(R.id.editText);
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) {
        //Check if the entered character is the first character of the input
        if(start == 0 && before == 0){
            //Get the input
            String input = s.toString();
            //Capitalize the input (you can also use StringUtils here)
            String output = input.substring(0,1).toUpperCase() + input.substring(1);
            //Set the capitalized input as the editText text
            editText.setText(output);
            //Set the cursor at the end of the first character
            editText.setSelection(1);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
});

请注意,如果您确实需要在不支持首字母大写标准方式的键盘上完成工作,这只是一种解决方法。

它将输入的第一个字符大写(忽略数字和特殊字符)。唯一的缺陷是,键盘的输入(在我们的例子中是 Gboard)仍然显示小写字母。

有关 onTextChanged 参数的详细说明,请参阅答案。

于 2019-04-16T09:14:00.287 回答