如何通过单击方向按钮移动onDraw形状

时间:2014-09-21 03:05:07

标签: java android onclick onclicklistener

我在Android上做模拟器来模拟我们机器人的移动(在这种情况下用圆圈表示)。单击向前/向右/向左按钮时,圆圈应向前移动,向右转或向左转。 但是当我运行这个程序并单击按钮时,圆圈没有移动......

在主要活动中,我有像这样的onClickListener:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    findViewById(R.id.forward_button).setOnClickListener(mGlobal_OnClickListener);
    findViewById(R.id.right_button).setOnClickListener(mGlobal_OnClickListener);
    findViewById(R.id.left_button).setOnClickListener(mGlobal_OnClickListener);


}


 View.OnClickListener mGlobal_OnClickListener = new View.OnClickListener() {
    public void onClick(View v) {
        GameView gameView = new GameView(Menu.this);
        switch(v.getId()) {
            case R.id.forward_button:
                gameView.controlRobot(GameView.FORWARD);
                break;
            case R.id.right_button:
                gameView.controlRobot(GameView.RIGHT);
                break;
            case R.id.left_button:
                gameView.controlRobot(GameView.LEFT);


        }
    }
};

在扩展View类的GamaView类中,我画了一个这样的圆圈:

canvas.drawCircle((currentX * cellHeight)+(cellHeight/2),   //x of center
            (currentY * cellHeight)+(cellHeight/2),  //y of center
            (cellHeight*3*0.45f),                           //radius
            robot);

同样在GameView类中我有这个controlRobot方法来移动这个圆圈: (移动/旋转方法是正确的。我已经测试过了)

public boolean controlRobot(int keyCode) {
    boolean moved = false;
    boolean rotated = false;

    //move(0):move up on the map
    //move(3):move right on the map
    //move(6):move down on the map
    //move(9):move left on the map

        //forward
    switch (keyCode) {
        case FORWARD:
            if(rotate_count%12==0)
                moved = maze.move(0);

            if(rotate_count%12==3)
                moved = maze.move(3);
            if(rotate_count%12==6)
                moved = maze.move(6);
            if(rotate_count%12==9)
                moved = maze.move(9);
            break;
        case RIGHT:
            rotated = maze.rotate(Maze.RIGHT,rotate_count);
            if(rotated)
            rotate_count+=3;
            break;
        case LEFT:
            rotated = maze.rotate(Maze.LEFT,rotate_count);
            if(rotated)
            rotate_count-=3;
            break;
    }


    if(moved||rotated) {
        //the ball was moved so we'll redraw the view
        invalidate();
    }
    return true;
}

1 个答案:

答案 0 :(得分:0)

当您在onclick中引用GameView时就像这样

GameView gameView = new GameView(Menu.this);

这不是布局文件中的GameView

R.layout.main

尝试在onClick中引用GameView,就像按下按钮一样

findViewById(R.id.forward_button)

除了布局文件中的GameView的R.id