Android简单游戏。在游戏视图上添加图像按钮

时间:2016-09-16 13:02:09

标签: java android

是否有将按钮/图像按钮放在“游戏表面”的顶部? 我正在尝试使用此博客中的代码: https://www.simplifiedcoding.net/android-game-development-tutorial-1/

我需要用一些按钮改变屏幕上对象的方向。 在本教程中,如果在任何地方按下触摸屏,船只会改变方向。

我试过这个: ImageButton b1 =(ImageButton)findViewById(R.id.turn_left); 为了稍后使用addView将视图添加到视图中,但它返回null。 也许是因为setContentView(gameView);设置GameView的视图而不是 GameActivity? 关于如何使这项工作的任何建议?

public class GameActivity extends AppCompatActivity  {

    private GameView gameView;

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

    //Getting display object
    Display display = getWindowManager().getDefaultDisplay();

    //Getting the screen resolution into point object
    Point size = new Point();
    display.getSize(size);

    gameView = new GameView(this, size.x, size.y);

    //adding it to contentview
    setContentView(gameView);
}

GameView

public class GameView extends SurfaceView implements Runnable { 
     ...code...
     private void draw() {

    //checking if surface is valid
    if (surfaceHolder.getSurface().isValid()) {
        //locking the canvas
        canvas = surfaceHolder.lockCanvas();
        //drawing a background color for canvas
        canvas.drawColor(Color.BLACK);
        //Drawing the player
        canvas.drawBitmap(
                ...code...
                draw);
        //Unlocking the canvas
        surfaceHolder.unlockCanvasAndPost(canvas);
    }
}
....code....
 @Override
public boolean onTouchEvent(MotionEvent motionEvent) {
    switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_UP:
         ...code...
    return true;
    }
}

XML          

xmlns:tools="http://schemas.android.com/tools"
tools:context="package.GameActivity">

<ImageButton
    android:id="@+id/turn_left"
    android:background="@drawable/left"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

1 个答案:

答案 0 :(得分:1)

您可以创建通过画布绘制位图的自定义按钮类。

相关问题