带有GBoard输入的EditText的首字母大写

时间:2017-08-08 19:12:55

标签: java android android-keypad capitalization gboard

我试图设置"首字母大写" progrommaticaly (因为我在EditText中设置了ListView

有很多与此问题相关的话题,最有名的是that我猜。我已经尝试了那里提供的解决方案和

setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)

真有帮助。例外 - 当用户使用GBoard (谷歌键盘)时,它无法提供帮助。 (自动大写未关闭)

那么,是否可以让它适用于GBoard?或者......如果press shift中没有文字,可以edittext进行推进吗?

1 个答案:

答案 0 :(得分: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) {
    }
});

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

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

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

相关问题