2

I want to identify which key is pressed from the keyboard while type text into EditText box. I am using this code, but it is not working.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    if (keyCode == KeyEvent.KEYCODE_SPACE) {

        Toast.makeText(MainActivity.this, "White space is clicked", Toast.LENGTH_LONG).show();
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

where i am getting wrong?

faisal ahsan
  • 41
  • 2
  • 10

2 Answers2

3

you can try the following code----

editText1.addTextChangedListener(new TextWatcher() {

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO Auto-generated method stub
        String lastChar = s.toString().substring(s.length() - 1);
        if (lastChar.equals(" ")) {
            Toast.makeText(MainActivity.this, "space bar pressed",
                    Toast.LENGTH_SHORT).show();
        }
    }

});

}

RajSharma
  • 1,941
  • 3
  • 21
  • 34
  • If Keyboard is providing suggestions, On white space pressed, it is showing suggestions. check out this link. this problem Arrived. – Prasad PH Dec 05 '18 at 09:51
0

try this, it might help you

boolean userPressedKey = false ;

yourEditText.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) {
        userPressedKey = false ;
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        userPressedKey = true;
    }); 


public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (userPressedKey) {
        if (keyCode == KeyEvent.KEYCODE_SPACE) {
    Toast.makeText(MainActivity.this, "White space is clicked", Toast.LENGTH_LONG).show();
            return true;
        }
    }
    super.onKeyDown(keyCode, event);
}
dlohani
  • 2,511
  • 16
  • 21
  • i am entering data in EditText, now what i want is when user hits SpaceBar then new word start with a special character like "$". Thats every word in EditText after space should have first letter as "$". – Tara Mar 01 '16 at 10:26