简体   繁体   English

如何在片段内使用 2 秒的计时器?

[英]How can I use a Timer of 2 seconds inside a fragment?

This is my Fragment.kt

class SplashFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_splash, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
            // My Timer
            Timer().schedule(object : TimerTask() {
                override fun run() {
                    findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
                }
            }, 2000)

    }
}

This is my Logcat error

2022-02-06 20:37:34.755 27478-27510/com.finite.livelocationtest E/AndroidRuntime: FATAL EXCEPTION: Timer-0
    Process: com.finite.livelocationtest, PID: 27478
    java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
        at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
        at android.widget.Toast.getLooper(Toast.java:179)
        at android.widget.Toast.<init>(Toast.java:164)
        at android.widget.Toast.makeText(Toast.java:492)
        at android.widget.Toast.makeText(Toast.java:480)
        at com.finite.livelocationtest.ui.fragment.SplashFragment$onViewCreated$1.run(SplashFragment.kt:31)
        at java.util.TimerThread.mainLoop(Timer.java:562)
        at java.util.TimerThread.run(Timer.java:512)

What do I want to achieve?我想达到什么目的?

I want to go from this fragment to the next fragment after a time of 2 seconds time, please let me know any possible way to achieve this.我想在 2 秒后从这个片段到下一个片段 go,请让我知道任何可能的方法来实现这一点。

The exception that you have included tells me you are trying to display a Toast<\/code> on a non-UI thread.您包含的异常告诉我您正在尝试在非 UI 线程上显示Toast<\/code> 。 I'm not seeing any toast call in your example, bud please note that you CANNOT show a Toast on non-UI thread.我在您的示例中没有看到任何 toast 调用,请注意,您不能在非 UI 线程上显示 Toast。 You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread.您需要从主线程中调用 Toast.makeText() (以及处理 UI 的大多数其他函数)。

"

Instead of trying to use Timer class, we can use coroutines.我们可以使用协程,而不是尝试使用 Timer 类。

lifecycleScope.launch {
  delay(2000)
  findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
}

just use the Android Handler for 2-second delay.只需使用 Android 处理程序进行 2 秒延迟。 Here is the code sample这是代码示例

Handler(Looper.getMainLooper()).postDelayed({
   //this portion is run when the handler is completing 2 second of delay
}, 2000)

Works on both activity and fragment适用于活动和片段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM