在我的Android应用中,我有不同的
EditText
,用户可以在其中输入信息。但我需要强制用户使用大写字母进行书写。您知道一个能实现这个功能的函数吗?EditText
,用户可以在其中输入信息。但我需要强制用户使用大写字母进行书写。您知道一个能实现这个功能的函数吗?
edit_text.filters = edit_text.filters + InputFilter.AllCaps()
使用合成属性直接访问具有ID的小部件。 在XML中,对于您的编辑文本,请添加一些更多的标志:
<EditText
android:id="@+id/edit_text_qr_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...other attributes...
android:textAllCaps="true"
android:inputType="textCapCharacters"
/>
editText.filters = editText.filters + InputFilter.AllCaps()
XML :
android:inputType="textCapCharacters" with Edittext
edittext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
@Override
public void afterTextChanged(Editable et) {
String s=et.toString();
if(!s.equals(s.toUpperCase()))
{
s=s.toUpperCase();
edittext.setText(s);
}
editText.setSelection(editText.getText().length());
}
});
只需要这样做:
// ****** Every first letter capital in word *********
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapWords"
/>
//***** if all letters are capital ************
android:inputType="textCapCharacters"
简单的 Kotlin 实现
fun EditText.onlyUppercase() {
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
filters = arrayOf(InputFilter.AllCaps())
}
PS,看起来filters
最初总是为空
尝试这段代码,它会将输入转换为大写字母
edittext.setFilters(new InputFilter[] {new InputFilter.AllCaps()});
基于被接受的答案,这个答案使用Kotlin做同样的事情。只是为了方便复制粘贴 :·)
private fun EditText.autocapitalize() {
val allCapsFilter = InputFilter.AllCaps()
setFilters(getFilters() + allCapsFilter)
}
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:inputType="textCapCharacters"
/>
<EditText
android:id="@+id/et"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:hint="Input your country"
android:padding="10dp"
android:inputType="textCapCharacters"
/>
android:inputType =“textCapCharacters”
时,AllCaps键盘在Android 6.0上出现了,但在Android 5.1上没有。 我在我的axml中添加了android:textAllCaps =“true”
,但在Android 5.1上仍然没有AllCaps键盘。 我使用 EditText.SetFilters(new IInputFilter[] { new InputFilterAllCaps() });
设置过滤器,虽然在Android 5.1上软键盘显示小写字符,但输入字段现在是AllCaps。SetFilters(new IInputFilter[] { new InputFilterAllCaps() });
,输入是All Caps。
filters += InputFilter.AllCaps()
:D - crgarridos