要将 FrameLayout 替换为 CoordinatorLayout,您可以创建自定义 NavHostFrament 并覆盖 onCreateView 方法。
NavHostFragment 内部:
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
FrameLayout frameLayout = new FrameLayout(inflater.getContext());
// When added via XML, this has no effect (since this FrameLayout is given the ID
// automatically), but this ensures that the View exists as part of this Fragment's View
// hierarchy in cases where the NavHostFragment is added programmatically as is required
// for child fragment transactions
frameLayout.setId(getId());
return frameLayout;
}
如您所见,FrameLayout 是通过编程方式创建的,并且在返回之前设置了它的 id。
CustomNavHostFragment:
class CustomNavHostFragment : NavHostFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// change it to CoordinatorLayout
val view = CoordinatorLayout(inflater.context)
view.id = id
return view
}
}
但是,您不需要将 NavHostFragment 的默认 FrameLayout 替换为 CoordinatorLayout。根据 Ian Lake 的answer 也可以实现ViewCompat.setOnApplyWindowInsetsListener() 来拦截对窗口插入的调用并进行必要的调整。
coordinatorLayout?.let {
ViewCompat.setOnApplyWindowInsetsListener(it) { v, insets ->
ViewCompat.onApplyWindowInsets(
v, insets.replaceSystemWindowInsets(
insets.systemWindowInsetLeft, 0,
insets.systemWindowInsetRight, insets.systemWindowInsetBottom
)
)
insets // return original insets to pass them down in view hierarchy or remove this line if you want to pass modified insets down the stream.
// or
// insets.consumeSystemWindowInsets()
}
}