删除edittext的最后一个字符

时间:2012-09-28 08:50:47

标签: 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()行中的东西?

2 个答案:

答案 0 :(得分: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));
    }
});

答案 1 :(得分:8)

尝试一下,

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


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

    yourEditText.setText ( str );
}
相关问题