2014-09-21 101 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