我找到了解决办法。我们不传递片段,而是包含片段的类和参数(
Class<T>
和
Bundle
然后,我们创建并添加片段
onViewCreated()
class BaseCustomDialogFragment: Fragment() {
companion object {
val FRAGMENT_CLASS = "FRAGMENT_CLASS"
val ARGUMENTS_BUNDLE = "ARGUMENTS_BUNDLE"
fun <T> getInstance(title: String, fragmentClass: Class<T>, bundle: Bundle): BaseCustomDialogFragment {
return BaseCustomDialogFragment().apply {
arguments = Bundle()
arguments!!.putString(DIALOG_TITLE, title)
arguments!!.putSerializable(FRAGMENT_CLASS, fragmentClass)
arguments!!.putBundle(ARGUMENTS_BUNDLE, bundle)
}
}
}
private lateinit var className: Class<*>
private lateinit var bundle: Bundle
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
(arguments?.getSerializable(FRAGMENT_CLASS) as? Class<*>)?.let { className = it }
arguments?.getBundle(ARGUMENTS_BUNDLE)?.let { bundle = it }
// Inflate View.
return inflater.inflate(R.layout.fragment_custom_dialog, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setContentUp()
}
private fun setContentUp(){
val fragment = createFragment(className, bundle)
activity?.supportFragmentManager
?.beginTransaction()
?.add(R.id.fragment_dialog_placeholder, fragment)
?.disallowAddToBackStack()
?.commit()
}
private fun <T> createFragment(fragmentClass: Class<T>, arguments: Bundle): Fragment {
val fragment = fragmentClass.newInstance() as Fragment
fragment.arguments = arguments
return fragment
}
我希望对某人有帮助。