在谷歌kotlin代码实验室上进行调试介绍时,我无法摆脱这个未解决的引用错误



我试过浏览这个网站以及其他网站。我已经被这个问题困扰了大约两天了。如果有人知道我在这里做错了什么,我们将不胜感激。

这是代码

fun division() = with(Handler(Looper.getMainLooper())){
val numerator = 60
var denominator = 4
repeat(4) {i->
postDelayed({
findViewById<TextView>(R.id.division_textview).setText("${numerator / denominator}")
Log.v(TAG, "${numerator / denominator}")
denominator--
},i*3000L)

}
}
fun logging() {
Log.e(TAG, "ERROR: a serious error like an app crash")
Log.w(TAG, "WARN: warns about the potential for serious errors")
Log.i(TAG, "INFO: reporting technical information, such as an operation succeeding")
Log.d(TAG, "DEBUG: reporting technical information useful for debugging")
Log.v(TAG, "VERBOSE: more verbose than DEBUG logs")
}

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG,"this where the app crashed before")
val helloTextView: TextView = findViewById(R.id.division_textview )
Log.d(TAG, "this should be logged if the bug is fixed ")
helloTextView.text= "Hello, debugging "
logging()
division()

}

}

以下是他们在课程中提供的说明。

因此AFAIKfindViewById()是活动类的一部分,因此应该在活动或视图的范围内调用为了给你更多的澄清,让我举一个接近你代码的例子假设ActivityMutableList

使用Extension函数


fun division(){
flatMap {} //Error because its only accessible with in MutableList
}
fun MutableList<Int>.division(){
flatMap {} // works because its inside the MutableList
}

使用继承


class mList: MutableList<Int> {
// Implement the necessary members
fun division() {
flatMap {} //works because its under scope
}
}

所以几乎相同的想法适用于AppCompatActivity

扩展函数


fun MainActivty.divison(){
val numerator = 60
var denominator = 4
repeat(4) {i->
postDelayed({
findViewById<TextView>(R.id.division_textview).setText("${numerator / denominator}")
Log.v(TAG, "${numerator / denominator}")
denominator--
},i*3000L)

}
}

继承方法

class MainActivity: AppCompatActivity{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG,"this where the app crashed before")
val helloTextView: TextView = findViewById(R.id.division_textview )
Log.d(TAG, "this should be logged if the bug is fixed ")
helloTextView.text= "Hello, debugging "
logging()
division()

}
fun division() = with(Handler(Looper.getMainLooper())){
val numerator = 60
var denominator = 4
repeat(4) {i->
postDelayed({
findViewById<TextView>(R.id.division_textview).setText("${numerator / denominator}")
Log.v(TAG, "${numerator / denominator}")
denominator--
},i*3000L)

}
}

findViewById的新替代方案https://developer.android.com/topic/libraries/view-binding

最新更新