分段打包

时间:2018-08-17 10:06:20

标签: android kotlin fragment

我有一个片段,我想将其用作全屏或对话框内容。

我正试图通过这种方式:

companion object {
    val DIALOG_TITLE = "DIALOG_TITLE"
    fun getInstance(title: String, content: Fragment): BaseCustomDialogFragment {
        return BaseCustomDialogFragment().apply {
            arguments?.putString(DIALOG_TITLE, title)
            activity?.fragmentAdd(content)
        }
    }
}

显然,此解决方案无效。只要Fragment尚未附加,我们就无法访问该活动。

有什么方法可以在不触发Activity负载的情况下达到相同的结果?

1 个答案:

答案 0 :(得分:0)

我找到了解决方法。我们没有传递Fragment,而是包含Fragment的类和参数(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
}

我希望它对某人有帮助。