如何在活动类之外定义textview?

时间:2017-11-12 00:24:53

标签: android android-studio kotlin android-location

我有一个位置监听器对象,我想知道如何在活动类之外定义TextView。在LayoutInflater.from(context).inflate(R.layout.main, null)我得到了一个未解决的' context'和' main'。对于 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) {}
}

1 个答案:

答案 0 :(得分:2)

更改此行

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()