如何获得在EditText中键入的最后一个字符?

时间:2018-07-31 13:38:53

标签: android

我想知道用户何时输入空格字符,以便我知道更新撤消列表。

使用onKeyListener在虚拟键盘上不起作用(从概念上讲,这是错误的方法,我不在乎用户如何输入该空间,他可能已经粘贴了该空间)

TextWatcher仅提供全文,采用字符串的最后一个字符无济于事。用户最好在中间输入。如何获取最后插入的字符?

4 个答案:

答案 0 :(得分:3)

尝试一下:它应该为您解决。您可能需要添加更多错误检查。

edittext.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(final CharSequence s, int start, int before, int count) {
          //Char at newly inserted pos.
          String str = s.charAt(start + before);

        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
      });

答案 1 :(得分:1)

et1.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        // TODO Auto-generated method stub
    }

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

        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {

        // TODO Auto-generated method stub
    }
});

答案 2 :(得分:0)

您可以比较TextChanged事件之前和之后的字符串,以便查看发生了什么变化。此函数返回键入或删除的最后一个字符。

oldStrbeforeTextChanged中设置,而newStronTextChanged中设置。

这还会返回最后一个已删除字符。

public char lastCharTyped(String oldStr, String newStr){
    String shorter, longer;
    //find which string is shorter so that we don't end up out of bounds
    if (oldStr.length()<newStr.length() ) {
        shorter = oldStr;
        longer = newStr;
    } else {
        shorter = newStr;
        longer = oldStr;
    }

    //find the first character that is different and return it
    for (int i = 0; i < shorter.length(); i++) {
        if (longer.charAt(i) != shorter.charAt(i)) return longer.charAt(i);
    }

    //if no characters are different then return the last char of the longer string
    //this means that the undo will be saved if the last char the user erased is a space
    Log.d("longer",longer);
    return(longer.charAt(longer.length()-1));
}

答案 3 :(得分:0)

以下是在文本中输入“#”(特殊字符)时对“执行某些操作”的答案。

editText.addTextChangedListener(new TextWatcher() {
        
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //do nothing
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //do nothing
        }

        @Override
        public void afterTextChanged(Editable s) {
            String string = s.toString();
                if(string.contains("#")){
                    //do something
          }
        }

    });