我有一个位置侦听器对象,我想知道如何在 Activity 类之外定义TextView。在LayoutInflater.from(context).inflate(R.layout.main, null)
中,我获得了“上下文”和“主”的未解析引用。对于val locTextView = MainActivity.findViewById(R.id.locTextView) as TextView1
我获得了findViewById的未解决参考。
private val locationListener: LocationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
val v = LayoutInflater.from(context).inflate(R.layout.main, null)
val locTextView = MainActivity.findViewById(R.id.locTextView) as TextView
locTextView.setText("" + location.longitude + ":" + location.latitude);
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {}
}
最佳答案
改变你的这一行
val v = LayoutInflater.from(context).inflate(R.layout.main, null)
与
val v = LayoutInflater.from(applicationContext).inflate(R.layout.main, null)
然后再次
改变你的
MainActivity.findViewById(R.id.locTextView) as TextView
与
val locTextView = findViewById< TextView>(R.id.locTextView)
更新
如果您想使用Kotlin Android Extention,那就告别
findViewById()