在EditText中只允许使用1个字符,并在用户输入时始终覆盖

Sta*_*tan 7 android textwatcher android-edittext

我需要制作一个EditText只接受一个字符且只接受字符(字母/字母)的字符.如果用户输入其他char,则应替换现有的char(如使用1个允许的符号覆盖文本输入的方法).

  1. 我知道如何设置属性中文本的最大长度.但是如果我将其设置为1,则在用户删除现有字符之前不能插入其他字符.但我希望自动替换现有的char,而无需手动删除.怎么做?

  2. 我知道如何设置属性只允许数字EditText,但我无法弄清楚如何只允许字符.那么第二个问题是如何只允许字符EditText

目前我使用的EditText是最大文本大小= 2,代码如下:

final EditText editLetter = (EditText)findViewById(R.id.editHouseLetter); 
editLetter.addTextChangedListener(new TextWatcher() {

    public void afterTextChanged(Editable s) {
        if (s!=null && s.length()>1){
            editLetter.setText(s.subSequence(1, s.length()));
            editLetter.setSelection(1);
        }
    }

    public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {

    }

    public void onTextChanged(CharSequence s, int start, int before,
        int count) {

    }
});
Run Code Online (Sandbox Code Playgroud)

关键是,当用户输入第二个字符时,应删除第一个字符.将文本大小设置为2允许用户在输入一个字符后输入另一个字符.

我真的不明白它是如何工作的,但它确实:).此外,我不得不将光标指向EditText最后一个位置,因为它总是进入开始,这使得无法输入任何东西.不知道为什么会这样.

这个解决方案的要点是它有2个字符大小EditText,但我希望它有1个字符大小.并且它允许输入除字母之外的任何内容(字符/ alpha),除了字符我什么都不想要.

使用sgarmanCharacter.isLetter()function 提供的建议,afterTextChanged方法现在看起来像这样:

public void afterTextChanged(Editable s) {
    int iLen=s.length();
    if (iLen>0 && !Character.isLetter((s.charAt(iLen-1)))){
        s.delete(iLen-1, iLen);
        return;
    } 
    if (iLen>1){
        s.delete(0, 1);
    } 
}
Run Code Online (Sandbox Code Playgroud)

我发现Selection.setSelection在这种情况下不需要使用.现在它有一个过滤器,只允许输入字母.这几乎就是我想要的答案.剩下的唯一一件事就是如何用1个符号大小做同样的事情EditText

abd*_*.cu 11

你可以将这一行添加到你的布局xml文件中,android会为你做这些事情

android:maxLength="1"
Run Code Online (Sandbox Code Playgroud)

例如,你肯定应该将它作为属性添加到editText elemet中

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:maxLength="1" >
Run Code Online (Sandbox Code Playgroud)

我遇到了同样的问题,并发现这个更简单的解决方案,我知道这是一个老问题,但我决定把我的答案放在那些打开这个链接的人身上.

我不应该忘记感谢这个博客的老板,我引用了答案!

  • 请仔细阅读我的问题 - 它不仅限于1个字符的限制.你的方式不会工作. (7认同)

sga*_*man 4

尝试:

s.delete(0, 1);
Selection.setSelection(s, s.length());
Run Code Online (Sandbox Code Playgroud)