2011-05-26 39 views
3

我一直在討論Snake示例代碼,我試圖爲了培訓而對此進行修改,希望能夠增加對Android工作方式的理解。android - setOnClickListener;

到目前爲止,我已經添加了兩個按鈕+相應的setOnClickListener代碼,如下所示。

snake_layout.xml

  <Button 
     android:layout_height="39px" 
     android:layout_width="55px" 
     android:layout_marginLeft="15px" 
     android:text="Left" 
     android:id="@+id/left_button" /> 

     <Button 
     android:layout_height="39px" 
     android:layout_width="55px" 
     android:layout_marginLeft="240px" 
     android:text="Right" 
     android:id="@+id/right_button" /> 

Snake.java

. 
. 
. 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    // No Title bar 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 

    setContentView(R.layout.snake_layout); 

    final Button leftButton = (Button) findViewById(R.id.left_button); 
    leftButton.setOnClickListener(new Button.OnClickListener() { 
     public void onClick(View v) 
      { 
       //perform action 
      } 
     }); 

    final Button rightButton = (Button) findViewById(R.id.right_button); 
    rightButton.setOnClickListener(new Button.OnClickListener() { 
     public void onClick(View v) 
      { 
       //perform action 
      } 
     }); 
. 
. 
. 

兩個按鈕出現在那裏,當我嘗試一個簡單的方法,他們應該和工作,這樣的爲「finish()」。

現在,我想這樣做是讓這些按鈕觸發下面的代碼, 在SnakeView.java

 if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { 
     if (mDirection != EAST) { 
      mNextDirection = WEST; 
     } 
     return (true); 
    } 

    if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { 
     if (mDirection != WEST) { 
      mNextDirection = EAST; 
     } 
     return (true); 
    } 

要清楚,我需要我的屏幕上的定製按鈕執行與當前代碼中的「KEYCODE_DPAD_RIGHT」和「KEYCODE_DPAD_LEFT」相同的作業。 我的Xperia X10i沒有配備DPAD,這是它的一部分;-P

我真的很感謝在正確方向上的一些指針。正如你可能已經猜到我是相當新的這個..

在此先感謝球員

+0

我沒有看到一個問題或一個問題。你有什麼需要幫助的? – 2011-05-26 14:10:58

回答

1

入住這裏:

Throwing/Simulating KeyStrokes programatically

的基本邏輯背後隱藏:

private void doInjectKeyEvent(KeyEvent kEvent) { 
    try { 
     /* Inject the KeyEvent to the Window-Manager. */ 
     windowManager.injectKeyEvent(kEvent.isDown(), kEvent.getKeyCode(), 
      kEvent.getRepeatCount(), kEvent.getDownTime(), 
      kEvent.getEventTime(), true); 
    } catch (DeadObjectException e) { 
     e.printStackTrace(); 
    } 
} 
1

代替onClick方法中的// perform action,從現有代碼中複製相應的主體(例如,if (mDirection != EAST) mNextDirection = WEST;)。

另外,以像素爲單位指定按鈕尺寸被認爲是不好的做法。對於要在可能具有非常不同的像素密度和屏幕尺寸的設備上運行的代碼,這並不適用。讓按鈕根據它們所包含的內容來調整自己的尺寸會更好。

0

您需要在SnakeView.java中創建一個允許您更改mNextDirection的函數。

public void setMNextDirection(int direction){ 
    //check if the direction is recognised 
    if (direction == EAST || direction == WEST) { 
    mNextDirection = direction; 
    } 

後,您可以使用:

mSnakeView.setMNextDirection(mSnakeView.WEST);