我想在类中使用位图变量。它会导致“属性 getter 或 setter 预期”错误。问题是什么? 错误显示在 'bmp? :位图=空'。 我该如何解决这个问题?
而且我不明白为什么我必须对类中的私有(private)属性使用 getter 或 setter。
class MyView(context: Context?) : View(context) {
private var bmp? : Bitmap = null
init {
bmp = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawColor(Color.BLUE)
canvas?.drawBitmap(bmp,10f,10f, null)
}
}
最佳答案
问题是您要使用安全调用运算符创建 Nullable 对象,但您的语法是错误的。尽管将 ?
放置在变量中,您仍需要将其放置在引用类型中。
检查语法是否正确:
private var bmp : Bitmap? = null
然后你可以像下面这样使用安全调用运算符访问这个变量:
bmp?.someMethodCall() // This line will never throw you null pointer exception because of ? (Safe call operator)
查看更多 here .
关于android - 期望属性 getter 或 setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55604794/