如何解决Jetpack Compose:将视图添加到窗口管理器时崩溃
我试图将jetpack compose视图添加到窗口管理器以获取App覆盖视图。但是该应用程序崩溃了。我已经使用以下代码来添加jetpack撰写视图。当我尝试XML布局时,它工作正常。还有其他人遇到这个问题吗?预先感谢。
private val overlayWindowManager by lazy {
getSystemService(Context.WINDOW_SERVICE)
as WindowManager
}
private fun initwindowManager() {
val params = WindowManager.LayoutParams(
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,PixelFormat.TRANSLUCENT
)
params.gravity = Gravity.RIGHT or Gravity.TOP
overlayWindowManager.addView(ComposeView(this).apply {
setContent { Text("WINDOW") }
},params)
}
错误日志
java.lang.IllegalStateException: ViewTreeLifecycleOwner is not present in this window. Use ComponentActivity,FragmentActivity or AppCompatActivity to configure ViewTreeLifecycleOwner automatically,or call ViewTreeLifecycleOwner.set() for this View or an ancestor in the same window.
at androidx.compose.ui.platform.AbstractComposeView.onAttachedToWindow(ComposeView.kt:176)
at android.view.View.dispatchAttachedToWindow(View.java:20479)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3489)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2417)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1952)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8171)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:972)
at android.view.Choreographer.doCallbacks(Choreographer.java:796)
at android.view.Choreographer.doFrame(Choreographer.java:731)
at android.view.Choreographer$FramedisplayEventReceiver.run(Choreographer.java:957)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
解决方法
您的主要活动延伸到哪个班级?
看起来您的答案在堆栈跟踪的第一行
Use ComponentActivity,FragmentActivity or AppCompatActivity to configure ViewTreeLifecycleOwner automatically
或
call ViewTreeLifecycleOwner.set() for this View or an ancestor in the same window
使用ViewTreeLifecycleOwner.set()
:
windowManager.addView(ComposeView(this).apply {
ViewTreeLifecycleOwner.set(this,activity)
setContent { Text("WINDOW") }
},params)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。