首页 > 解决方案 > 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

}

标签: kotlinif-statement

解决方案


函数的最后一行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)
}

推荐阅读