2014-09-21 97 views
1

我在Android上模拟机器人的模拟器(在这种情况下用圆圈表示)。当点击前进/右/左按钮时,圆应该向前移动,向右转或向左转。 但是,当我运行这个程序,并单击按钮,圆没有动......如何通过点击方向按钮移动onDraw形状

在主要活动我有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); 


     } 
    } 
}; 

在GamaView类延伸查看类,我画像这样的循环:

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

而且在GameView I类有此controlRobot方法移动该圆: (移动/旋转的方法是正确的I已经测试它们)

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

是否将GameView放置在布局文件中,因为您在onClick方法中使用的GameView是全新的GameView – JRowan 2014-09-21 03:10:35

+0

@JRowan我将GameView放入一个布局文件。 GameView可以显示在用户界面上。但controlRobot方法不起作用。 – Baller 2014-09-22 06:22:20

+0

我提出了一个答案,当你setContentView()你从布局使用GameView,在你的onClick方法中,你没有从布局引用GameView – JRowan 2014-09-22 06:39:46

回答

0

当您参考GameView在你的onclick这样

GameView gameView = new GameView(Menu.this); 

,是不是在你的布局文件GameView

R.layout.main 

尝试引用GameView在你的onClick像你这样的按钮

findViewById(R.id.forward_button) 

除了在布局文件中使用Gameid的R.id