Android 删除edittext的最后一个字符
我有一个简短的问题 我有一个带有一些数字的屏幕,当你点击其中一个数字时,这个数字会被追加到编辑文本的末尾Android 删除edittext的最后一个字符,android,android-edittext,Android,Android Edittext,我有一个简短的问题 我有一个带有一些数字的屏幕,当你点击其中一个数字时,这个数字会被追加到编辑文本的末尾 input.append(number); 我还有一个backbutton,当用户单击此按钮时,我想删除最后一个字符 目前,我有以下几点: Editable currentText = input.getText(); if (currentText.length() > 0) { currentText.delete(currentText.length() - 1,
input.append(number);
我还有一个backbutton,当用户单击此按钮时,我想删除最后一个字符
目前,我有以下几点:
Editable currentText = input.getText();
if (currentText.length() > 0) {
currentText.delete(currentText.length() - 1,
currentText.length());
input.setText(currentText);
}
有没有更简单的方法?input.remove()行中的某些内容 试试这个
String str = yourEditText.getText().toString().trim();
if(str.length()!=0){
str = str.substring( 0, str.length() - 1 );
yourEditText.setText ( str );
}
我意识到这是一个老问题,但它仍然有效。如果您自己修剪文本,则在设置文本()时光标将重置为起始位置。因此,相反(如njzk2所述),发送一个假的delete key事件,让平台为您处理它
//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));
}
});
我会在内部注入一个带有del键的keyEvent,这并不简单,也不会检查边界。这会将光标设置在编辑文本的开头,这不是idealGood方法,它可以工作!需要注意的是,该代码仅模拟按“Delete”键。要使删除生效,
EditText
必须具有焦点。您可以使用editText.isFocused()
进行检查,并使用editText.requestFocus()
对其进行聚焦。它还会将光标放在末尾,因此会删除最后一个字符。如果android:enabled=“false”类似于最后一条注释,则将不起作用