How to send key event to an edit text

前端 未结 10 2261
醉酒成梦
醉酒成梦 2021-02-07 20:43

For example, send a backspace key to the edit text control to remove a character or send a char code like 112 to append a character in the edittext control programmatically.

10条回答
  •  长发绾君心
    2021-02-07 21:48

    if you want a click listener, the best way to do it is this:

    View textfield = findViewById(R.id.textfield);  
    textfield .setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) {  
    /*your code for the click event here*/ }});
    

    if you want a backspace button, do this:

    public void backSpace() {   
    EditText textfield = (EditText)findViewById(R.id.textfield);  
        try {  
            textfield.getText().delete(textfield.getSelectionEnd() - 1, textfield.getSelectionStart());  
        } catch (Exception e) {  
            try {  
                textfield.getText().delete(textfield.length() - 1, textfield.length());  
            } catch (Exception myException) {  
            //textfield.getText().delete(textfield.length(), textfield.length() - 1);  
            }  
        }  
    }
    

    if you want to append a character in the EditText, do this:

    EditText textfield = (EditText)findViewById(R.id.textfield);  
    textfield.setText(textfield.getText().concat("112"));
    

提交回复
热议问题