只接受字母并将EditText中的第一个字符大写

问题描述 投票:3回答:4

我需要一个EditText来只允许字母和大写第一个字符。

为了只允许字母,我在XML布局中设置属性android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "并且它正常工作。然后,我还设置属性android:inputType="textCapSentences"来大写第一个字母,但它没有用。

只是为了知道发生了什么,我试图删除digits属性,然后textCapSentences属性工作正常。

所以,问题是:我可以使用一个属性或另一个属性,但我无法让它们同时工作。我怎么解决这个问题?我可能需要以编程方式解决它吗?谢谢。

<EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
        android:inputType="textCapSentences"
        android:hint="@string/et_hint" />
android android-edittext
4个回答
1
投票

保留textCapSentences属性并以编程方式执行字母检查,如下所示:

et_name.setFilters(new InputFilter[] { filter }); 

InputFilter filter = new InputFilter() { 
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
    for (int i = start;i < end;i++) { 
        if (!Character.isLetter(source.charAt(0))) { 
            return ""; 
        } 
    } 
    return null; 
} 
}; 

1
投票

我不知道一起使用这两个属性,但如果一个单独工作,一个解决方案可能是在EditText上使用textCapSentences并编写文本过滤器,如下所示:

public static InputFilter[] myFilter = new InputFilter[] {
    new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            for (int i = start; i < end; i++) {
                if (!Character.isLetterOrDigit(source.charAt(i)) &&
                        source.charAt(i) != '@' &&
                        source.charAt(i) != '#') {
                    Log.i(TAG, "Invalid character: " + source.charAt(i));
                    return "";
                }
            }
            return null;
        }
    }
};

这个例子接受0-9,所有字母(大写和小写),以及charcters @和#,只是举个例子。如果你试图输入任何其他字符,它将返回“”,并基本上忽略它。

初始化编辑文本时应用它:

    EditText editText = (EditText) findViewById(R.id.my_text);
    editText.setFilters(myFilter);

0
投票

如果您希望将每个新单词大写,则应使用另一个inputType:

 android:inputType="textCapWords"

如果你想大写每个新句子的第一个字母,你可以将.添加到你的数字,它将帮助系统识别新句子:

 android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. "

0
投票

你可以为像这样的属性使用多个值android:inputType="textCapSentences|text"希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.