我有一个EditText,我需要其中的文本(当用户键入时)以大写字母开头。
Answers:
如果同时添加android:capitalize="sentences"和android:inputType="text",请小心,因为后者似乎优先于第一个,并且输入内容不会大写。
有一个inputType自动将首字母大写的方法:
android:inputType="textCapSentences"
参见http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
android:inputType="textMultiLine|textCapSentences"
android:capitalize的选项是
android:inputType="none", which won't automatically capitalize anything.
android:inputType="sentences", Which will capitalize the first word of each sentence.
android:inputType="words", Which Will Capitalize The First Letter Of Every Word.
android:inputType="characters", WHICH WILL CAPITALIZE EVERY CHARACTER.
显然,它已更改为inputType而不是capitalize
试试这个
testEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
或android:inputType="textCapSentences"仅在启用设备键盘的自动大写设置时才有效。
您使用了“强制”一词。所以尝试一下。只需将您的edittext作为参数传递即可。
public static void setCapitalizeTextWatcher(final EditText editText) {
final TextWatcher textWatcher = new TextWatcher() {
int mStart = 0;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mStart = start + count;
}
@Override
public void afterTextChanged(Editable s) {
String input = s.toString();
String capitalizedText;
if (input.length() < 1)
capitalizedText = input;
else
capitalizedText = input.substring(0, 1).toUpperCase() + input.substring(1);
if (!capitalizedText.equals(editText.getText().toString())) {
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) {
}
@Override
public void afterTextChanged(Editable s) {
editText.setSelection(mStart);
editText.removeTextChangedListener(this);
}
});
editText.setText(capitalizedText);
}
}
};
editText.addTextChangedListener(textWatcher);
}
在布局xml中,添加 android:capitalize="sentences"
如果密码以大写字母开头,则为:
android:inputType="textPassword|textCapSentences"
edittext.setFilters(new InputFilter[] {new InputFilter.AllCaps()});