xibic
xibic

Reputation: 27

How to read Directional Key Press and Do something in Android

i am trying to learn android app development. i want to move an object using up,down,right,left arrow key. please anyone helps me on how to read the pressed directional key and move the object.

Upvotes: 0

Views: 1859

Answers (2)

Jaydeep Khamar
Jaydeep Khamar

Reputation: 5985

Use this in your Activity

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



    if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN)
    {
        //your code
 return false;
    }
    if(keyCode==KeyEvent.KEYCODE_DPAD_CENTER)
    {
          /*yourcode*/                                          

return false;
    }
    if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT)
    {
        //your code                                         
return false;
    }
    if(keyCode==KeyEvent.KEYCODE_DPAD_RIGHT)
    {
        //your code                                         
return false;
    }
    if(keyCode==KeyEvent.KEYCODE_DPAD_UP)
    {
        //your code                                         
return false;
    }
    return super.onKeyDown(keyCode, event);
}

Edited code

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

    if(keyCode==KeyEvent.KeyEvent.KEYCODE_DPAD_CENTER)
    {
        Toast.makeText(<Activity_name>.this, "Application Quits", Toast.LENGTH_SHORT).show();
          finish();
          return false;
    }

    return super.onKeyDown(keyCode, event);
}

Upvotes: 1

Hamdullah shah
Hamdullah shah

Reputation: 654

override the onkeydown function and compare the keycode with KeyEvent.KEYCODE_DPAD_DOWN etccccc

Upvotes: 0

Related Questions