我想在屏幕上绘制文本,但是收到错误消息:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawText(java.lang.String, float, float, android.graphics.Paint)' on a null object reference
我的代码:
package com.example.root.runningmanv2
import android.content.Context
import android.graphics.Paint
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.SurfaceView
import android.view.WindowManager
class GamingActivity : AppCompatActivity() {
private lateinit var gameView: SurfaceGame
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//set fullscreen
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN)
gameView = SurfaceGame(this)
setContentView(gameView)
}
override fun onPause() {
super.onPause()
}
override fun onResume() {
super.onResume()
gameView.start()
}
inner class SurfaceGame(context: Context): SurfaceView(context), Runnable{
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
val ourHolder = holder
val canvas = ourHolder.lockCanvas()
fun start(){
val thread = Thread(this)
thread.start()
}
override fun run() {
drawFigure()
}
fun drawFigure(){
paint.setARGB(255, 255, 255, 255)
canvas.drawText("Hello", 500f, 500f, paint)
ourHolder.unlockCanvasAndPost(canvas)
}
}
}
如何解决?
答案 0 :(得分:0)
您自己从 SurfaceView.Callback
而不是在 SurfaceGame 类中获取 holderclass GamingActivity : SurfaceHolder.Callback, AppCompatActivity() {
private var holder: SurfaceHolder? = null
private var pos = 0
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val view = SurfaceView(this)
setContentView(view)
view.holder.addCallback(this)
}
override fun surfaceCreated(holder: SurfaceHolder) {
this.holder = holder
pos = 0
Thread({
while (this.holder != null) {
drawFigure(this.holder)
Thread.sleep(100)
}
}).start()
}
override fun surfaceChanged(holder: SurfaceHolder, frmt: Int, w: Int, h: Int) {
this.holder = holder
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
this.holder = null
}
private fun drawFigure(holder: SurfaceHolder?) {
if (holder == null) return
val canvas = holder.lockCanvas()
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.setARGB(255, 0, 0, 0)
paint.textSize = 96f
canvas.drawText("Hello", 100f + pos, 500f, paint)
pos++
holder.unlockCanvasAndPost(canvas)
}
}