[英]EditText which accepts only a few characters
我需要在 Android 上实现一个EditText
,它只接受特定范围的字符,即:“S、A、Q、W、R、B、C、D、E、U”。
What about using these two attributes in your EditText
在
EditText
使用这两个属性怎么样
android:maxLength="1"
android:digits = "SABCDEU"
Just use attribute android:maxLength="1"
, this will allow only one character input to edittext.只需使用属性
android:maxLength="1"
,这将只允许一个字符输入到编辑文本。
You can Use android:digits
property and specify in the XML itself what are the valid characters for you.您可以使用
android:digits
属性并在 XML 本身中指定什么是您的有效字符。
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:digits = "SABCDEU"
android:maxLength="1" >
You should use InputFilters你应该使用 InputFilters
edittext.setFilters(new InputFilter[] {
new InputFilter() {
public CharSequence filter(CharSequence src, int start,
int end, Spanned dst, int dstart, int dend) {
if(src.toString().matches("[a-zA-Z ]+")){
return src;
}
return "";
}
}});
Yes as below:是的,如下:
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:digits="SABCDEU"
android:maxLength="1" >
If you want to set the number of maximum characters edittext should accept then use this:如果要设置 edittext 应接受的最大字符数,请使用以下命令:
android:maxLength="1"
If you want to set specific characters edittext should accept then use this:如果要设置 edittext 应接受的特定字符,请使用以下命令:
android:digits = "character you want to accept"
in your case:在你的情况下:
android:digits = "SABCDEU"
here note that edittext will not accept numeric characters,space,lowercases and Uppercase except SABCDEU.这里请注意,除了 SABCDEU,edittext 不接受数字字符、空格、小写和大写。 You have to put all character in
android:digits=""
if you wish to enter to edittext.如果您想进入编辑文本,您必须将所有字符都放在
android:digits=""
。
Just add this piece of code in your Java
只需在您的 Java 中添加这段代码
public class MainActivity extends Activity {
private EditText editText;
private String blockCharacterSet = "~#^|$%&*!FGHIJKLMOPTWXYZ";
private InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source != null && blockCharacterSet.contains(("" + source))) {
return "";
}
return null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
editText.setFilters(new InputFilter[] { filter });
}
}
This will give you what you want.
这会给你你想要的。 This will let you select only "S,A,Q,W,R,B,C,D,E,U".
这将让您仅选择“S、A、Q、W、R、B、C、D、E、U”。
Use this code, it only allows characters使用此代码,它只允许字符
<EditText
android:inputType="text"
android:digits="SAQWRBCDEU"
android:hint="Only letters allowed" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.