Android EditText - Delete the last letter with a button

后端 未结 4 1876
我寻月下人不归
我寻月下人不归 2021-01-13 16:29

I have to buttons that writes A and B to an edittext. If there is something in the edittext how can I delete the last letters with the \"Del\" button? My layout:

<         


        
相关标签:
4条回答
  • 2021-01-13 17:08

    Setting new text#1

    CharSequence text = edittext.getText();
    edittext.setText(text.subSequence(0, text.length() - 1));
    

    Setting new text#2

    CharSequence text = v.getText();
    edittext.setText("");
    edittext.append(text, 0, text.length() - 1);
    

    Deleting editable

    int length = editText.getText().length();
    if (length > 0) {
        editText.getText().delete(length - 1, length);
    }
    

    Subsequencing editable

    int length = editText.getText().length();
    if (length > 0) {
        editText.getText().subSequence(0, length - 1);
    }
    

    Deleting by dispatching delete key event.

    edittext.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
    
    0 讨论(0)
  • 2021-01-13 17:09
    String text = editText.getText().toString();
    if(text.length() > 0){
      text = str.substring(0, str.length()-1);
       editText.setText(text);
    }
    
    0 讨论(0)
  • 2021-01-13 17:18

    one limitation of others answer is if cursor not in last position then also it delete the last character that limitation is removed in this answer Write down at your on click of button

    int end = ((EditText)findViewById(R.id.one)).getSelectionEnd();
     if(end>0){
               SpannableStringBuilder selectedStr = new SpannableStringBuilder(((EditText) findViewById(R.id.one)).getText());
               selectedStr.replace(end - 1, end, "");
               ((EditText) findViewById(R.id.one)).setText(selectedStr);
               ((EditText) findViewById(R.id.one)).setSelection(end-1);
            }
    
    0 讨论(0)
  • 2021-01-13 17:21

    Yes you can create an onClickListener and just get the text from edit text and delete the last character.

    Button delete = (Button) findViewById(R.id.buttondel);
    if( delete != null ) {
       delete.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick() {
             String textString = editText.getText().toString();
             if( textString.length() > 0 ) {
                editText.setText(textString.substring(0, textString.length() - 1 ));
                editText.setSelection(editText.getText().length());//position cursor at the end of the line
             }
          }
       });
    }
    

    Edit: Also don't forget to check the string length is greater than 0 before doing this in the event a or b hasn't been pressed when the user hits delete.

    0 讨论(0)
提交回复
热议问题