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,r开发者_高级运维ight,left arrow key. please anyone helps me on how to read the pressed directional key and move the object.
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);
}
override the onkeydown function and compare the keycode with KeyEvent.KEYCODE_DPAD_DOWN etccccc
精彩评论