[英]Accept only letters and capitalize first character in EditText
我需要一個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" />
我不知道一起使用這兩個屬性,但如果一個單獨工作,一個解決方案可能是在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);
保留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;
}
};
如果您希望將每個新單詞大寫,則應使用另一個inputType:
android:inputType="textCapWords"
如果要將每個新句子的第一個字母大寫,可以添加.
對於你的數字,它將幫助系統識別新的句子:
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. "
你可以為這個屬性使用多個值,如android:inputType="textCapSentences|text"
希望這會android:inputType="textCapSentences|text"
幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.