心血来潮复习官方文档发现检测fragment规范的办法检查竟然找
全局开启错误规范检查
FragmentStrictMode.Policy.Builder builder = new FragmentStrictMode.Policy.Builder();
builder.detectFragmentReuse()
.detectFragmentTagUsage()
.detectRetainInstanceUsage()
.detectSetUserVisibleHint()
.detectTargetFragmentUsage()
.detectWrongFragmentContainer();
// Fail early on DEBUG builds
builder.penaltyListener((exception) ->
Log.e(TAG,"FRAGMENG USE EXCEPTION",exception)
);
// builder.penaltyDeath();
FragmentStrictMode.INSTANCE.setDefaultPolicy(builder.build());
运行后发现了一个错误
to container android.widget.FrameLayout{30905a6 V.E...... ......I. 0,0-0,0 #7f0902a7 app:id/nav_host_fragment_activity_main} which is not a FragmentContainerView
at androidx.fragment.app.strictmode.FragmentStrictMode.onWrongFragmentContainer(FragmentStrictMode.kt:204)
问题原因:
错误的 fragment 容器
错误的 fragment 容器违规行为的检测是使用 detectWrongFragmentContainer() 启用的,当发生这种违规行为时,系统会抛出 WrongFragmentContainerViolation。
这种违规行为表示将 Fragment 添加到了除 FragmentContainerView 之外的容器。与 Fragment 标记使用一样,除非托管在 FragmentContainerView 内,否则 fragment 事务可能无法按预期运行。使用容器视图还有助于解决 View API 中的一个问题,该问题会导致将使用退出动画的 fragment 绘制在其他所有 fragment 之上。
参考
https://proandroiddev.com/android-fragments-fragmentcontainerview-292f393f9ccf
https://developer.android.com/guide/fragments/debugging?hl=zh-cn