我对android studio有非常基本的了解,并且只使用按钮和其他触发器开发了应用程序。我正在寻找创建一个我可以使用移动精灵的应用程序。我认为,从在线内容来看,我应该考虑使用SurfaceViews,但是似乎无法理解与SurfaceView相关的任何事情,或者为sprite创建和使用不同的类。
我目前正在尝试使用SurfaceView简单地更改活动的颜色,但目前甚至无法做到这一点!感谢任何帮助,在答案中请解释正在做什么,以便我能理解答案! :P
代码如下:
活动XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.Frenchie.TestSpaceGame.GameActivity">
<com.Frenchie.TestSpaceGame.GameView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
GameActivity.java
package com.Frenchie.TestSpaceGame;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class GameActivity extends AppCompatActivity {
private GameView gameView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new GameView(this);
setContentView(gameView);
}
}
GameView.java
package com.Frenchie.TestSpaceGame;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private Canvas canvas;
private SurfaceHolder surfaceHolder;
public GameView(Context context) {
super(context);
surfaceHolder = getHolder();
draw();
}
private void draw() {
//check if surface is valid
if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.YELLOW);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
GameActivity打开时,我的屏幕显示为黑屏。