简体   繁体   English

在Kotlin中动态更改textView值

[英]Changing the textView value dynamically in Kotlin

I have timed proximity sensors changes as 我已将定时接近传感器更改为

 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")
}

which is present in my ProximityDetector.kt file 这存在于我的ProximityDetector.kt文件中

and displaying it on my App using 并使用

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

which is in my SettingsActivity.kt file 在我的SettingsActivity.kt文件中

But it shows values for only one sensor change, for subsequent sensor changes the app needs to be withdrawn and opened again. 但是它仅显示一次传感器更改的值,对于后续的传感器更改,需要撤消并再次打开应用程序。 How to display the values for each sensor change??? 如何显示每个传感器变化的值??? I tried using this way 我尝试使用这种方式

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

but it shows Modifier 'override' is not applicable in local function 但它表明修饰符“覆盖”不适用于本地功能

Create interface in ProximityDetector.kt file. 在ProximityDetector.kt文件中创建interface

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

Implement it in SettingsActivity.kt file. 在SettingsActivity.kt文件中实现它。

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

Pass the SettingsActivity reference in ProximityDetector class constructor and assign it. ProximityDetector类构造函数中传递SettingsActivity引用并对其进行分配。

class ProximityDetector constructor(var onSensorValueChange: ProximityDetector.OnSensorValueChange)

and call method of interface to update value. 并调用接口的方法来更新值。

    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.
}  

In kotlin don't use getters and setters as like in java.The correct format of the kotlin is given below. 在kotlin中,不要像在Java中那样使用getter和setters。下面给出了kotlin的正确格式。

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

To get the values from the Textview we have to use this method 要从Textview获取值,我们必须使用此方法

val str: String = textView.text.toString()

 println("the value is $str")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM