当我运行应用程序和使用它没有崩溃。BottomSheetBehavior
工作正常。但如果我返回应用程序后,在后台暂停了很长一段时间,它崩溃与空点异常时,试图铸造view.parent as View
,以找到与BottomSheetBehavior
的视图。
为什么片段在暂停后没有父项?如何修复?
我试着做binding.root.parent as View
和其他requireActivity().findViewById(R.id.fragment_sheet_container)
。但是相同的情况连续崩溃。
@AndroidEntryPoint
class ToolboxSheetFragment : Fragment(R.layout.fragment_toolbox_sheet) {
private lateinit var binding: FragmentToolboxSheetBinding
private lateinit var behavior: BottomSheetBehavior<View>
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentToolboxSheetBinding.bind(view)
behavior = BottomSheetBehavior.from(
view.parent as View // null cannot be cast to non-null type android.view.View
)
}
fragment的父级是具有下一个布局的主Activity:
第一个
3条答案
按热度按时间kt06eoxx1#
如果我能得到完整的项目就更好了。但我在这里建议几种方法:
方式1:
把
behavior
放在Activity类里面怎么样?示例化它onCreate()
。然后像这样从ToolboxSheetFragment
使用它。然后从
ToolboxSheetFragment
方式二:
在
ToolboxSheetFragment
上使用addOnAttachStateChangeListener
:pnwntuvh2#
首先在
onCreateView()
中扩展布局,然后可以在onViewCreated()
中完成所有与视图相关的工作。e3bfsja23#
请不要忽略
savedInstanceState
,并确保Fragment
甚至连接到任何Context
。抱歉,没有提供功能完整的答案;例如,onAttached()
可以确定Fragment
是附加的-并且savedInstanceState
可能是也可能不是null
。并且当view.parent
为空时,View
可能不存在,它可能是MainActivity
的behavior
,而不是ToolboxSheetFragment
,这不是一回事。