kotlin - kotlin 通过使用 if 条件和时间来创建可见性
问题描述
我将可见性设置为单击时消失的图像视图,并且我希望它在未单击 1 秒时不可见。提前致谢。[我不想使用 postdelayed,因为它在这里不能正常工作,所以我想用 if 语句来做]
fun hideImages() {
runnable = Runnable {
for (image in imageArray) {
image.visibility = View.INVISIBLE
}
val random = Random()
val index = random.nextInt(8 - 0)
imageArray[index].visibility = View.VISIBLE
handler.postDelayed(runnable, 1000)
}
handler.post(runnable)
}
fun increaseScore(view: View) {
score++
txScore.text = "Score: " + score
for (image in imageArray){
image.visibility = View.GONE
}
for (image in imageArray) {
image.visibility = View.INVISIBLE
}
val random = Random()
val index = random.nextInt(8 - 0)
imageArray[index].visibility = View.VISIBLE
}
解决方案
函数的最后一行hideImages
立即发布您的可运行文件,不会有任何延迟,因此其中的代码将立即运行。然后它会延迟再次发布自己,因此它将每 1000 毫秒重复运行一次。您应该只在 Runnable 之外发布一次,然后延迟发布。并且您可能希望在每次单击按钮时延迟最多 1000 毫秒,因此您应该删除可运行文件并重新发布它。
fun hideImagesAfterDelay() {
handler.removeCallbacks(runnable)
runnable = Runnable {
for (image in imageArray) {
image.visibility = View.INVISIBLE
}
val index = Random.nextInt(8 - 0)
imageArray[index].visibility = View.VISIBLE
}
handler.postDelayed(runnable, 1000)
}
我不确定您在做什么,但也许您希望所有视图立即可见,其中一个视图稍后消失。在这种情况下,您应该使它们同步可见(在 Runnable 之外):
fun hideImagesAfterDelay() {
handler.removeCallbacks(runnable)
for (image in imageArray) {
image.visibility = View.INVISIBLE
}
runnable = Runnable {
val index = Random.nextInt(8 - 0)
imageArray[index].visibility = View.VISIBLE
}
handler.postDelayed(runnable, 1000)
}
推荐阅读
- python - 如何读取文本文件并转换为列表以与 Python 中的统计数据包一起使用
- python - 遍历字典以创建列表
- flutter - IOWebSocketChannel 检测连接何时打开
- c# - 为什么 TextBox1_Click 在尝试对文本进行单击事件时不起作用?
- jquery - 选中复选框时如何更新滑块最大值
- gradle - 如何从独立插件将类文件添加到 Gradle 源集?
- c++ - 在矩阵逆变器上工作,我的指数循环由于某种原因无法工作
- regex - 正则表达式:如何在某个单词之后按字母顺序查找任意长度的单词
- java - 我的 res 文件夹不断收到一条错误消息:错误:R 类是公共的,应在名为 R.java 的文件中声明
- machine-learning - 10个epoch的训练和5个epoch的两次训练效果一样吗?