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)
我想達到什么目標?
我想在 2 秒后從這個片段轉到下一個片段,請告訴我任何可能的方法來實作這一點。
uj5u.com熱心網友回復:
您包含的例外告訴我您正在嘗試Toast在非 UI 執行緒上顯示 a 。我在您的示例中沒有看到任何 toast 呼叫,請注意,您不能在非 UI 執行緒上顯示 Toast。您需要從主執行緒中呼叫 Toast.makeText() (以及處理 UI 的大多數其他函式)。
uj5u.com熱心網友回復:
我們可以使用協程,而不是嘗試使用 Timer 類。
lifecycleScope.launch {
delay(2000)
findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
}
使用它解決了我遇到的問題,我的應用程式崩潰的原因是我試圖從后臺執行緒執行 UI 相關的事情,因為它是一個非 UI 執行緒,所以它不起作用,所以我們需要做它在主執行緒上。
uj5u.com熱心網友回復:
只需使用 Android 處理程式延遲 2 秒。這是代碼示例
Handler(Looper.getMainLooper()).postDelayed({
//this portion is run when the handler is completing 2 second of delay
}, 2000)
適用于活動和片段
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/424644.html
