0

I am trying to control a segway remotely using WASD controls from a bluetooth keyboard. For now, I am trying to test that the device can register the keys being held down and print text only while the key is held down.

I have it working so that when the key is pressed, the text is printed to the screen, however, the text stays even after the key has been released. Eventually, I am going to have each key trigger a different velocity setting on the robot, but for now, I need to know that my code is able to detect and act appropriately when a key is held down versus when the key is released.

I have tried looking for some sort of isPressed() boolean method that can be called to tell me whether or not the key is being held down, but have been unable to do so.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    TextView key = (TextView) findViewById(R.id.textView);

    switch(keyCode){

        case KeyEvent.KEYCODE_W: //will eventually move robot forwards
            key.setText("forwards");
            return true;

        case KeyEvent.KEYCODE_S: //will eventually move robot backwards
            key.setText("backwards");
            return true;

        case KeyEvent.KEYCODE_D: //will eventually turn robot right
            key.setText("right turn");
            return true;

        case KeyEvent.KEYCODE_A: //will eventually turn robot left
            key.setText("left turn");
            return true;

        case KeyEvent.KEYCODE_DEL: //will eventually stop movement
            key.setText("");
            return true;
    }
    return super.onKeyDown(keyCode, event);
}

I expect that when I run the app, the text will only show up in the textview when the key is held down. Otherwise, the textview will be blank or will contain a "" (blank) string.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • do you have some kind of "onKeyUp" callback? The time between a keyDown and a keyUp may be your "keyPressed" time.. – aran Jul 10 '19 at 07:43
  • @aran thanks! not sure why I didn't think of that. that solved the issue. – Kabir Madan Jul 10 '19 at 07:50
  • glad to help mate! there's some interesting info here as well :) https://stackoverflow.com/questions/12950215/onkeydown-and-onkeylongpress – aran Jul 10 '19 at 07:50

0 Answers0