Android EditText/TextView如何让每个单词以大写开头,单词的所有剩余字符都为小写

标签 android android-edittext uppercase lowercase

我已经使用以下选项将单词的每个首字母设为大写

 <EditText
    android:inputType="text|textCapWords"/>

在键入时,用户可以在键盘上选择更改字母的大小写,即具有此选项的用户可以轻松地键入 lowercase 字母。

此外,我希望我的 EditText 上的文本采用这种格式

单词的每个起始字母必须大写,单词的所有其他字母必须小写

意思是,当用户输入

单词的每个起始字母必须大写,单词的所有其他字母必须小写

,会自动转换成上面的格式。

我已经尝试使用 TextWatcherstring.split(\\s+) 来获取所有单词,然后让每个单词都遵循上述格式。但我总是以错误告终。 因此,如果有任何解决方案,那就太好了。我希望它以 InputFilter.AllCaps 的方式工作。

到目前为止,这是我的代码

private void changeToUpperCase(String inputString) {
    if (inputString != null && inputString.trim().length() > 0) {
        // businessName.addTextChangedListener(null);
        String[] splitString = inputString.split("\\s+");
        int length = splitString.length;
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            String convertedString = splitString[i];
            stringBuffer.append(Character.toUpperCase(convertedString
                    .charAt(0)));
            stringBuffer.append(convertedString.substring(1).toLowerCase());
            stringBuffer.append(" ");
        }
        Log.i("changed String", stringBuffer.toString());
        // businessName.setText(stringBuffer.toString());
        stringBuffer.delete(0, stringBuffer.length());
        stringBuffer = null;
        // businessName.addTextChangedListener(this);
    }
}

我从 TextWatcher 调用这个函数,afterTextChanged(Editable s)

最佳答案

在布局xml中,添加android:capitalize="sentences"

android:capitalize 的选项如下:

android:capitalize="none" :不会自动大写任何内容。

android:capitalize="sentences" :将每个句子的第一个单词大写。

android:capitalize="words" :将每个单词的首字母大写。

android:capitalize="characters" :这将大写每个字符。

更新:

由于 android:capitalize 已弃用,现在需要使用:

android:inputType="textCapWords"

关于Android EditText/TextView如何让每个单词以大写开头,单词的所有剩余字符都为小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21155111/

相关文章:

Android AlarmManager 设置功能不起作用?

android - 我怎样才能从这个 JSON 字符串中删除这个符号?

Android EditText 无限文本长度

php - PHP 文件中的大写链接

android - jQuery Mobile/Phonegap - 选择菜单不会在 android 上打开

android - 即使应用程序被终止,flutter_background_geolocation 也会获取位置吗?

java - 如何在 Android 应用程序中使用 AsYouTypeFormatter TextWatcher?

Android 创建对齐字段布局

javascript - 在这种情况下,多维数组值分配如何工作?

powershell - 如何使用Powershell将csv文件转换为小写或大写,以保持其结构?