Question

I have an EditText and when a user uses the enter key it creates a new line. I want the enter key to only make a single space, not a new line. I have no idea to do this. The reason I want to is because when the user clicks Enter it creates a new line and when they submit the message its stored and the database with an empty line and then when its retrieved and displayed on the android phone it displays and empty line.

Was it helpful?

Solution

Try this:

 final EditText edittext = (EditText) findViewById(R.id.edittext);
    edittext.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                (keyCode == KeyEvent.KEYCODE_ENTER)) {
              // Perform action on key press
              editText.setText(editText.getText() + " ");
              return true;
            }
            return true;
        }
    });

OTHER TIPS

Try this way works perfectly

EditText edit = (EditText) findViewById(R.id.edit);

        InputFilter filter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

                for (int i = start; i < end; i++) {

                    if (source.charAt(i) == '\n') {
                        return " ";
                    }
                }
                return null;
            }
        };

        edit.setFilters(new InputFilter[] { filter });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top