Kotlin-延迟设置进度条

问题描述

我正在尝试做到这一点,以便在用户输入文本后旋转在我的edittext字段中放置的进度条。进度栏应继续旋转,直到用户一秒钟未输入更多文本为止。 (如果用户继续输入文字,则进度栏应继续旋转。)我正在使用textWatcher:

et_username_username.addTextChangedListener(object: TextWatcher {
        override fun afterTextChanged(p0: Editable?) {}

        override fun beforeTextChanged(p0: CharSequence?,p1: Int,p2: Int,p3: Int) {}

        override fun onTextChanged(p0: CharSequence?,p3: Int) {

            pb_username_progress_bar.visibility = View.VISIBLE
            val updatedText = p0.toString().trim().toLowerCase()

        CoroutineScope(IO).launch{
            
            delay(1000)

            pb_username_progress_bar.visibitlity = View.INVISIBLE
            //updates UI based on firebase database code
}

            }



    })

但是,当我运行此程序时,协程每次都在不同的线程上运行,因此当用户持续键入一秒钟以上时,进度条就会消失。
我如何做到这一点,以便当用户继续键入内容,协程是最佳方式还是其他方式时,进度条将停留在该位置?

(创建新帐户时,它看起来应该非常像instagram,创建用户名时它的旋转进度栏如何)

解决方法

您可以使用以下代码段作为解决方案。它将解决您的问题。

edit_search.addTextChangedListener(object : TextWatcher {
        private var searchFor = ""
        override fun afterTextChanged(s: Editable?) {
        }

        override fun beforeTextChanged(s: CharSequence?,start: Int,count: Int,after: Int) {
        }

        override fun onTextChanged(s: CharSequence?,before: Int,count: Int) {
            val searchText = s.toString().trim()
            if (searchText == searchFor)
                return
            searchFor = searchText
            progress_bar.visibility = View.VISIBLE
            CoroutineScope(IO).launch {
                delay(1000)
                if (searchText != searchFor)
                    return@launch
                progress_bar.visibility = View.INVISIBLE
            }
        }
    })

快乐编码:)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...