android - 删除编辑文本的最后一个字符

标签 android android-edittext

我有一个简短的问题。

我有一个带有一些数字的屏幕,当您单击其中一个数字时,该数字会附加到编辑文本的末尾。

input.append(number);

我还有一个后退按钮,当用户单击此按钮时我想删除最后一个字符。

目前我有以下内容:

Editable currentText = input.getText();

if (currentText.length() > 0) {
    currentText.delete(currentText.length() - 1,
            currentText.length());
    input.setText(currentText);
}

有没有更简单的方法来做到这一点? input.remove() 中的内容?

最佳答案

我意识到这是一个老问题,但它仍然有效。如果您自己修剪文本,当您设置文本() 时,光标将重置为开始。因此(如 njzk2 所述),发送一个假的删除键事件并让平台为您处理它......

//get a reference to both your backButton and editText field

EditText editText = (EditText) layout.findViewById(R.id.text);
ImageButton backButton = (ImageButton) layout.findViewById(R.id.back_button);

//then get a BaseInputConnection associated with the editText field

BaseInputConnection textFieldInputConnection = new BaseInputConnection(editText, true);

//then in the onClick listener for the backButton, send the fake delete key

backButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        textFieldInputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
    }
});

关于android - 删除编辑文本的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12636665/

相关文章:

android - 快门声停止

Android View setPadding() 与 setPaddingRelative()

android - 自定义字体错误

android - 在android中输入编辑文本时删除特殊字符;

Android:如何在聚焦时将 ScrollView 中的 EditText 放在另一个 View 上方?

java - 如何获取EditText中选中的光标位置?

java - 如何在 EditText 中插入文本?

php - 如何遍历这个?

android - 如何在相对度量中指定 Android GridLayout 单元格的宽度和高度?

Android 编辑文本光标不可见?