两个小时精通Android开发之按键映射篇
作者:孙东风 2010-01-07(转载务必注明出处)
笔者的上篇文章《两个小时精通Android开发》中讲解了利用Android的接口规范开发J2ME的Wrap包,从而解决了J2ME程序无法运行在Android平台上的技术难题,但是Android平台和J2ME另一个重要的不同点就是按键响应接口,如何让J2ME程序的按键响应可以无缝的移植到Android上呢?答案也是Wrap包。
笔者这里通过按键映射把Android平台的键盘码转换成J2ME平台的键盘码,或者把Android平台的触摸事件通过代理传递给J2ME中相应的接口。
首先,需要在Android平台的GameCanvas里进行如下定义:
public class GameCanvas extends Screen {
public static final int UP = 1;
public static final int DOWN = 6;
public static final int LEFT = 2;
public static final int RIGHT = 5;
public static final int FIRE = 8;
public static final int GAME_A = 9;
public static final int GAME_B = 10;
public static final int GAME_C = 11;
public static final int GAME_D = 12;
public static final int KEY_NUM0 = 48;
public static final int KEY_NUM1 = 49;
public static final int KEY_NUM2 = 50;
public static final int KEY_NUM3 = 51;
public static final int KEY_NUM4 = 52;
public static final int KEY_NUM5 = 53;
public static final int KEY_NUM6 = 54;
public static final int KEY_NUM7 = 55;
public static final int KEY_NUM8 = 56;
public static final int KEY_NUM9 = 57;
public static final int KEY_STAR = 42;
public static final int KEY_POUND = 35;
}
当然,为了适配J2ME里的接口笔者还定义如下的接口:
protected abstract void keyRepeated(int keyCode);
protected abstract void keyPressed(int keyCode);
protected abstract void keyReleased(int keyCode);
protected abstract void pointerPressed(int x, int y);
protected abstract void pointerReleased(int x, int y)
protected abstract void pointerDragged(int x, int y);
笔者在上面定义的都是J2ME的视图类Canvas里的按键响应接口,这里需要做的工作就是把Android里的按键进行映射转换成J2ME里的标准键值后传递给这些接口,并由继承自GameCanvas的界面类进行实现,完全和J2ME里一样了,基本不用修改任何代码。
键值映射的代码如下:
public int keyActual = 0;
public int keyAction = 0;
public void keyPreparse(int keyCode,KeyEvent e)
{
if(keyCode == KeyEvent.KEYCODE_0)
{
keyActual = GameCanvas.KEY_NUM0;
}else if(keyCode == KeyEvent.KEYCODE_1)
{
keyActual = GameCanvas.KEY_NUM1;
}else if(keyCode == KeyEvent.KEYCODE_2)
{
keyActual = GameCanvas.KEY_N
相关新闻>>
- 发表评论
-
- 最新评论 更多>>