简体   繁体   中英

Android Problem: EditText, KeyListener and the physical Back Button

My activity implements KeyListener and my edittext has a key listener set.

editor = new EditText(this);
        editor.setMinLines(4);
        editor.setMinimumWidth(400);
        editor.setKeyListener(this);

WHen the user types something and presses "enter" on the softkeyboard a textview's text is set to the users input.

@Override
public int getInputType() {

    return InputType.TYPE_TEXT_FLAG_MULTI_LINE;
}


@Override
public boolean onKeyDown(View view, Editable text, int keyCode,
        KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_ENTER){

        outview.setText(editor.getText());
    }
    return true;
}

Here outview is a TextView. My problem is that in this activity the physical back button doesn't work. Press it and nothing happens. ANy advice would be welcomed.

By returning true from the onKeyDown function, you are informing Android that you have handled all key events. Instead, only return true in the case of the enter key. Return false otherwise. This will allow Android to handle the back button key press.

find enter of softkeyboard

txt.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) 
        {
                  outview.setText(editor.getText());
        }
        return true;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM