【问题标题】:TextWatcher - Backspace key on empty EditTextTextWatcher - 空 EditText 上的退格键
【发布时间】:2018-04-14 06:52:17
【问题描述】:

我正在开发一个远程控制应用程序,我有一个片段,我在其中添加了一个 EditText 字段以捕获关键事件,因为我需要将信息发送到在我的笔记本电脑上运行的服务器,所以字母并且可以在我的笔记本电脑的屏幕上看到其他字符。 当 EditText 为空时,我无法使用退格键,因此无法删除屏幕上已存在的文本。如果我在 EditText 字段中输入了一些文本并且按下了退格键,则检测到退格键事件。

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

    previousTextLength = s.length();


}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    char ch = newCharacter(s, previousText);
    if (ch == 0) {
        return;
    }
    MainActivity.sendMessageToServer("TYPE_CHARACTER");
    MainActivity.sendMessageToServer(Character.toString(ch));

}

@Override
public void afterTextChanged(Editable s) {


}

private char newCharacter(CharSequence currentText, CharSequence previousText) {
    char ch = 0;
    currentTextLength = currentText.length();

    int difference = currentTextLength - previousTextLength;
    if (currentTextLength > previousTextLength) {
        if (1 == difference) {
            ch = currentText.charAt(previousTextLength);
        }
    } else if (currentTextLength < previousTextLength) {
        if (-1 == difference) {
            ch = '\b';
        } else {
            ch = ' ';
        }
    }
    return ch;
}

【问题讨论】:

  • 是否需要将每个字符发送到服务器,或者编辑完成后发送数据?
  • 另外,当编辑文本为空时,您希望按退格键做什么。
  • 当编辑文本为空时,我希望可以选择删除屏幕上已经存在的信息。现在,如果编辑文本为空并且我按退格键没有任何反应,但如果我已经在编辑文本中输入了一个单词,则该单词将显示在我的屏幕上,当我按下退格键时,我可以将其删除。数据会立即发送,因此无需先键入单词并点击“发送”按钮。我可以将每个字符发送到服务器。

标签: android textwatcher


【解决方案1】:

您可以使用onKeyListener 来检测是否按下了退格键,如下所示:

editText.setOnKeyListener(new OnKeyListener() {                 
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_DEL) {  
            //Perform action for backspace
        }
        return false;       
    }
});

【讨论】:

  • 我试过你的代码,但是现在如果编辑文本是空的,当我按下退格按钮时,发送到服务器的字符是字母“c”。因此,它不会删除屏幕上已经存在的文本,而是添加字母“c”。
  • 你是如何从退格获得字符的?
  • 我用过 '\b' 。
  • 那应该没问题。检查你将字符发送到服务器的逻辑。我的代码完成的工作只是提供退格键按下。它不会干扰你的逻辑
  • 我试过 Character.toString('\b') 不能转换成 'c'
【解决方案2】:

也许作为一种变通方法,您可以强制 EditText 的第一个字符为 [SPACE] 或您想要的任何提示字符..

@Override
public void afterTextChanged(Editable s) {
    // You can replace ' ' and " " with any character you want. For example '>'
    if(s.length() == 0 || s.charAt(0) != ' ') {
        s.insert(0, " ");
    }
}


您可能希望强制光标保持在索引 0 之前...

editText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(editText.getSelectionStart() == 0) {
            editText.setSelection(1);
        }
    }
});

您可能需要进行适当的更改以忽略s.insert(0, " "),以免将其发送到服务器。

【讨论】:

    猜你喜欢
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多