Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Handle Enter Key Using TextWatcher on Android

I am working on Android. Previously i used onKeyListener to handle specific action on key event.

However, this way seems not to solve my problem since almost all key would get disable once i have implemented that listener to my EditText. After reading some topics in SO, i know that i should use TextWatcher instead, but i'm still wondering how to handle ENTER key event inside because parameters provided there are only CharSequence, Editable, etc. I didn't find any keyCode parameters.

like image 321
M Rijalul Kahfi Avatar asked Oct 14 '12 10:10

M Rijalul Kahfi


3 Answers

try this

protected View.OnKeyListener onEnter = new View.OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if ((event.getAction() == KeyEvent.ACTION_DOWN)
                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
            //here do what you want
        }
        return false; // very important
    }
};
like image 77
Mohsin Naeem Avatar answered Oct 07 '22 08:10

Mohsin Naeem


try this

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if (s.length()>0 && s.subSequence(s.length()-1, s.length()).toString().equalsIgnoreCase("\n")) {
        //enter pressed
    }
}
like image 32
user2348959 Avatar answered Oct 07 '22 09:10

user2348959


I think this is the better solution, because you can press 'Enter' in any place of your EditText field and not only at the end of line.

    edittext.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int st, int ct,
                                      int af) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() < 1 || start >= s.length() || start < 0)
                return;

            // If it was Enter
            if (s.subSequence(start, start + 1).toString().equalsIgnoreCase("\n")) {

                // Change text to show without '\n'
                String s_text = start > 0 ? s.subSequence(0, start).toString() : "";
                s_text += start < s.length() ? s.subSequence(start + 1, s.length()).toString() : "";
                edittext.setText(s_text);

                // Move cursor to the end of the line
                edittext.setSelection(s_text.length());
            }
        }
    });
like image 1
Pavel Kataykin Avatar answered Oct 07 '22 09:10

Pavel Kataykin