【问题标题】:Kotlin - Setting up a progress bar with delayKotlin - 设置延迟的进度条
【发布时间】:2020-09-10 05:50:38
【问题描述】:

我正在尝试使我放入编辑文本字段的进度条在用户输入文本后旋转。进度条应该继续旋转,直到用户一秒钟内没有输入任何文本。 (如果用户一直在输入文本,进度条应该会一直旋转。)我正在使用 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?, p1: Int, p2: Int, 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,它在创建用户名时它是如何旋转进度条的)

【问题讨论】:

  • 你可以使用 Handler.postDelayed 来在 UI 线程上做一些事情。或在启动块中使用 pb_username_progress_bar.post() 在 UI 线程上工作

标签: android android-studio kotlin coroutine


【解决方案1】:

您可以使用以下代码 sn-p 作为解决方案。它会解决你的问题。

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?, start: Int, 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
            }
        }
    })

快乐编码:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多