android - 尝试使用 Kotlin 在 Android Studio 中延迟后执行行
问题描述
您好,我有 textView 元素,我正在尝试通过延迟更改其文本。例如“你好” -> 等待 1 秒 -> “世界” -> 等待 1 秒 -> “你好吗?”
当我在终端中的单独 kotlin 文件中使用我的代码时,它完全按照我想要的方式工作。当我在 MainActivity.kt 中使用代码时,它会等待 1 秒并且只放置一次文本值。我认为它同时执行所有行。但是为什么终端和ui之间存在差异。
我的代码在 Main Activity 中有一个类文件和代码
class Ball (val Ball: TextView, val time: Long){
fun textChange(){
Handler().postDelayed({
Ball.text = (1..90).random().toString()
}, time)
}
}
在 MainActivity
class MainActivity : AppCompatActivity() {
var resultsList = mutableListOf<Int>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fun playButtonPressed(view:View){
Ball(Ball01,1000).textChange()
Ball(Ball01,1000).textChange()
Ball(Ball01,1000).textChange()
Ball(Ball01,1000).textChange()
Ball(Ball01,1000).textChange()
}
}
解决方案
这样做,您要求显示 5 个字符串,但延迟相同。
在我看来,您必须使用CountDownTimer以定期间隔显示另一段文本。
这是一个示例代码
class Ball (val Ball: TextView, val messagesList: List<String>){
private var index = 0
fun textChange(interval: Long) {
val time = interval * messagesList.size
val timer = object: CountDownTimer(time, interval) {
override fun onTick(millisUntilFinished: Long) {
Ball.append(" " +messagesList[index++])
}
override fun onFinish() {
//nothing to do
}
}
timer.start()
}
}
class MainActivity : AppCompatActivity() {
var messageList = mutableListOf<String>("Hello", "World", "How are you ?")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fun playButtonPressed(view:View){
// will update the text every second during until the list is empty
Ball(textView, messageList).textChange(1000)
}
}
推荐阅读
- java - 如何使用springboot微服务创建两个实体
- python - pysftp Paramiko PasswordRequiredException:私钥文件已加密
- ios - Swift - Firebase - 异步下载图像和数据会导致集合视图单元格中的错误显示
- python - 没有元数据的 Dask read_parquet 分区
- python - Amazon s3 文件下载“TypeError:预期的字符串或类似字节的对象”
- python - 生成一定长度的整数(字节大小也可以)
- r-markdown - rmarkdown 中字体大小意外翻倍
- python - 如果它们是某个值,则将列中的值替换为来自不同列的值
- r - R:通过 rbindlist + cmd 读取许多压缩文件
- python - 熊猫键中的值问题