在Kotlin中动态更改textView值

我有时间接近传感器更改为

override fun onSensorChanged(event: SensorEvent) { val distance = event.values[0] val max = event.sensor.maximumRange a = System.currentTimeMillis() if (distance < Math.min(max, 8.toFloat())) { listener.onNear() } else { listener.onFar() } b = System.currentTimeMillis() System.out.println("That took " + (b- a) + " milliseconds") } 

它出现在我的ProximityDetector.kt文件中

并使用我的应用程序显示它

 timeTaken.setText("That took " + (b - a) + " milliseconds") 

这是在我的SettingsActivity.kt文件

但它只显示一个传感器变化的值,对于随后的传感器变化,应用程序需要被撤回并再次打开。 如何显示每个传感器的值更改? 我试着用这种方式

 override fun onSensorChanged(event: SensorEvent) { timeTaken.setText("That took " + (b - a) + " milliseconds")} 

但是它显示修饰符“覆盖”不适用于本地function

在kotlin中不要像在java中那样使用getter和setter。下面给出了kotlin的正确格式。

 val textView: TextView = findViewById(R.id.android_text) as TextView textView.setOnClickListener { textView.text = getString(R.string.name) } 

为了从Textview中获取值,我们必须使用这个方法

 val str: String = textView.text.toString() println("the value is $str") 

在ProximityDetector.kt文件中创建interface

 interface OnSensorValueChange{ fun onValueChange(value: Long); } 

在SettingsActivity.kt文件中实现它。

 override fun onValueChange(value: Long) { timeTaken.setText("That took " + value + " milliseconds") } 

ProximityDetector类构造函数中传递SettingsActivity引用并分配它。

 class ProximityDetector constructor(var onSensorValueChange: ProximityDetector.OnSensorValueChange) 

并调用接口的方法来更新值。

  override fun onSensorChanged(event: SensorEvent) { val distance = event.values[0] val max = event.sensor.maximumRange a = System.currentTimeMillis() if (distance < Math.min(max, 8.toFloat())) { listener.onNear() } else { listener.onFar() } b = System.currentTimeMillis() System.out.println("That took " + (b- a) + " milliseconds") onSensorValueChange.onValueChange((b- a)) //add this line. }