删除edittext的最后一个字符

Rob*_*met 5 android android-edittext

我有一个快速的问题.

我有一个带有一些数字的屏幕,当你点击其中一个数字时,数字会附加到edittext的末尾.

input.append(number);
Run Code Online (Sandbox Code Playgroud)

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

目前我有以下内容:

Editable currentText = input.getText();

if (currentText.length() > 0) {
    currentText.delete(currentText.length() - 1,
            currentText.length());
    input.setText(currentText);
}
Run Code Online (Sandbox Code Playgroud)

有更简单的方法吗?input.remove()行中的东西?

小智 11

我意识到这是一个古老的问题,但它仍然有效.如果您自己修剪文本,则在setText()时光标将重置为开头.所以相反(如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));
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 好的方法,它的工作!有一点需要注意,代码*只模拟*按"删除"键.要使删除工作,`EditText`必须具有焦点.您可以使用`editText.isFocused()`进行检查,并使用`editText.requestFocus()`来聚焦它.它还会将光标放在末尾,因此它将删除最后一个字符. (3认同)

Luc*_*fer 8

试试这个,

String str = yourEditText.getText().toString().trim();


   if(str.length()!=0){
    str  = str.substring( 0, str.length() - 1 ); 

    yourEditText.setText ( str );
}
Run Code Online (Sandbox Code Playgroud)

  • 这并不简单,也不检查边界. (3认同)