Android DialogFragment getDialog() 和 getView() 返回 null

问题描述 投票:0回答:2

我有一个 DialogFragment,我需要从片段中显示它。这是我的 DialogFragment:

class MyDialogFragment : DialogFragment() {
    companion object {
        @JvmStatic
        internal fun newInstance(): MyDialogFragment = MyDialogFragment()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
        inflater.inflate(R.layout.my_dialog_fragment container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.findViewById<MaterialButton>(R.id.cancel_button)?.setOnClickListener { dismiss() }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val builder = AlertDialog.Builder(requireActivity())
        val dialogView = requireActivity().layoutInflater.inflate(R.layout.my_dialog_fragment, null)
        builder.setView(dialogView)

        dialogView.findViewById<Button>(R.id.cancel_button).setOnClickListener { dismiss() }

        return builder.create()
    }

    fun setMyAction(action: () -> Unit) {
        view?.findViewById<MaterialButton>(R.id.proceed_button)?.setOnClickListener { action() }
    }
}

我从片段中调用它的方式是这样的:

btnSubmit.setOnClickListener(view -> {
            MyDialogFragment myDialogFragment = new MyDialogFragment();
            myDialogFragment.show(getChildFragmentManager(), MyDialogFragment.class.getSimpleName());
            myDialogFragment.setMyAction(this::action);
        });

我在这里遇到的问题是不可能从调用片段调用

setMyAction
并调用
action()
,因为在对话框中,
view
null
就像我尝试用
dialog()得到它一样
.这里的第二个问题是:为什么
onCreateView
从未被调用,就像
onViewCreated
一样?

提前致谢!

android kotlin android-dialogfragment
2个回答
3
投票

我在这里遇到的问题是无法从调用片段调用 setMyAction 并调用 action(),因为在对话框中,视图为空,就像我尝试使用 dialog() 获取它一样。

你现在遇到的问题是

show()
是异步的。该对话框将在稍后创建,而不是在
show()
返回时创建。

您尚未遇到但将会遇到的问题是,在配置更改时,默认情况下将重新创建您的活动及其片段,并且您的

OnClickListener
将丢失。

而不是将事件处理程序推入,让

DialogFragment
公开结果(例如,通过共享
ViewModel
)。

这里的第二个问题是:为什么从未调用过 onCreateView,就像 onViewCreated 一样?

你超越了

onCreateDialog()
。您不能同时使用
onCreateDialog()
onCreateView()
/
onViewCreated()
。选择一个并使用它。


0
投票

当我只是通过日志检查对话框是否打开及其返回空值时,我会遇到半问题。所以我只是在下面添加行,它工作正常。

如果您在片段中显示对话框,则使用 like

DialogFragment dialogFragment = new DialogFragment();  
dialogFragment.show(requireActivity().getSupportFragmentManager(),"Dialog");  
requireActivity().getSupportFragmentManager().executePendingTransactions();

如果您在活动中显示对话框,则无需使用 requireActivity()。

© www.soinside.com 2019 - 2024. All rights reserved.