Search code examples
androidandroid-edittextenter

EditText is not detecting keys


In a Fragment Class I've put this code in the onCreateView to monitor if the user presses ENTER, but its not working and its not even capturing any other keyboard press. N.B.: I'm testing on a virtual emulator.

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_sub, container, false);


        EditText addProduct = (EditText)rootView.findViewById(R.id.editText1);
        addProduct.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.i("any button","button");
                // if keydown and "enter" is pressed
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    ((EditText)v).setText("");
                    Log.i("here","im here");
                    return true;

                } else if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_9)) {

                    ((EditText)v).setText("");
                    Log.i("or here","9");
                    return true;
                }
                //do your stuff here against pressing shift key

                return false;
            }
        });
        return rootView;
        }

Solution

  • The onKey function only detects hardware keys, not soft keys. For an onscreen keyboard, you need to implement a TextWatcher.