【问题标题】:How do I define a textview outside of the activity class?如何在活动类之外定义文本视图?
【发布时间】:2018-04-24 22:47:53
【问题描述】:

我有一个位置侦听器对象,我想知道如何在活动类之外定义一个 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) {}
}

【问题讨论】:

    标签: android android-studio kotlin android-location


    【解决方案1】:

    改变你的这一行

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      • 2019-06-16
      • 1970-01-01
      相关资源
      最近更新 更多