如何在Kotlin的Android Studio中在几秒钟内自动移动一个活动到另一个活动[复制]

noj0wjuj  于 2023-04-07  发布在  Kotlin
关注(0)|答案(1)|浏览(159)

此问题已在此处有答案

How to call a function after delay in Kotlin?(15个回答)
2天前关闭。
我无法在Kotlin(android studio)中在几秒钟内自动从一个Activity移动到另一个Activity。你能回答我如何才能这样移动吗
Kotlinandroid studio中的Automaticallt move

bvhaajcl

bvhaajcl1#

https://developer.android.com/topic/libraries/architecture/coroutines#lifecyclescope

lifeCyclerScope.launch {
        viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.CREATED) {
            launch {
                delay(5000) //milisec
            //after 5 sec delay do it !

            } 
        }

如果您不需要某个活动,可以使用片段和片段导航
https://developer.android.com/guide/navigation/navigation-getting-started
生命周期仪和导航示例

class MyFragment: Fragment {
    init { // Notice that we can safely launch in the constructor of the Fragment.
        lifecycleScope.launch {
            whenStarted {
                // The block inside will run only when Lifecycle is at least STARTED.
                // It will start executing when fragment is started and
                // can call other suspend methods.
                loadingView.visibility = View.VISIBLE
                val canAccess = withContext(Dispatchers.IO) {
                    checkUserAccess()
                }

                // When checkUserAccess returns, the next line is automatically
                // suspended if the Lifecycle is not *at least* STARTED.
                // We could safely run fragment transactions because we know the
                // code won't run unless the lifecycle is at least STARTED.
                loadingView.visibility = View.GONE
                if (canAccess == false) {
                    findNavController().popBackStack()
                } else {
                    showContent()
                }
            }

            // This line runs only after the whenStarted block above has completed.

        }
    }
   }

相关问题