所以我正在撰寫一段代碼,將暫停和恢復功能添加到抽象類 CountDownTimer (Android.os.CountDownTimer) 中。我只在這個活動中使用該功能,因此我只是使用物件運算式來創建一個名為 sequencetimer 的匿名類。代碼看起來像這樣:
public var sequencetimer = object : CountDownTimer(30000, 1000) {
public var timeremaining : Long = 0
override fun onTick(millisUntilFinished: Long) {
findViewById<TextView>(R.id.textView8).apply {
text = ("seconds remaining: " millisUntilFinished / 1000)
}
}
override fun onFinish() {
findViewById<TextView>(R.id.textView8).apply {
text = "done"
}
}
public fun pauseTimer() {
timeremaining = findViewById<TextView>(R.id.textView8).text as Long
cancel()
}
public fun resumeTimer() {
onTick(timeremaining)
start()
}
}
現在我想呼叫我在活動暫停或恢復時添加的 pauseTimer 和 resumeTimer 函式,如下所示:
override fun onPause() {
super.onPause()
sequencetimer.pauseTimer()
}
override fun onResume() {
super.onResume()
sequencetimer.resumeTimer()
}
然而,即使在活動類中宣告了 sequencetimer 物件并且我可以執行所有其他函式,例如 sequencetimer.onTick() 和 sequencetimer,代碼仍然向我拋出函式 pauseTimer() 和 resumeTimer() 的未解決參考錯誤。 start() (但是我也不能訪問公共 var timeremaining)。有誰知道這里的問題是什么?還是根本不可能在匿名物件運算式中擴展/擴展抽象類(我本來希望 android studio 然后拋出某種型別的錯誤)?
uj5u.com熱心網友回復:
正如您自己所說:您創建匿名類。這意味著從開發人員的角度來看這個類不存在,并且型別sequencetimer只是CountDownTimer沒有pauseTimer()和resumeTimer()功能。您需要創建一個常規的命名類,以便在代碼中參考它。
或者,您可以制作sequencetimer一個private var. 在這種情況下,Kotlin 假設這是內部的東西,并提供了某種捷徑。它有條件地允許這種操作,即使通常它不應該是可能的。檔案中描述了此行為:https ://kotlinlang.org/docs/object-declarations.html#using-anonymous-objects-as-return-and-value-types
uj5u.com熱心網友回復:
您的代碼存在一些問題。
我看到的第一個問題是public var sequencetimer. 使用 kotlin 關鍵字public, protected, internal,您可以向編譯器宣告,這些關鍵字sequencetimer可以在您的 android 活動類范圍之外訪問。但object在您的活動類中創建為匿名類。Kotlin 編譯器決定唯一的解決方案是標記sequencetimer為CountDownTimer.
// byte code
public final getSequencetimer()Landroid/os/CountDownTimer;
@Lorg/jetbrains/annotations/NotNull;()
其次,resumeTimer()將呼叫onTick(12345L)一次并從 millisInFuture 重新啟動計時器30_000L。
最好為剩余時間創建一個新的倒計時計時器。請減少倒計時間隔,否則您會看到秒數不一致30, 28, 27, 26, 26, 24, ...
希望能幫助到你。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/454454.html
上一篇:應用圖示影像資產AndroidStudio的尺寸應該是多少?
下一篇:“由java.lang.reflect.invocationtargetexception引起”在android簽名生成生成期間出現錯誤
