在对话框打开时更改 DialogFragment 布局

Changing DialogFragment Layouts while dialog is open

我有一个 Android Activity,我想从中显示一个 Dialog。这可能是一个习惯 DialogFragment。现在,当用户单击特定按钮时,我希望 dialog 内的 layout's 随前一个 DialogFragment 的数据发生变化,这样它就可以返回到前一个Layout.

我不认为有一种简单的方法可以在同一个 DialogFragment 中更改视图,那么最好的方法是什么?

我已经尝试在方法 onViewCreated 中执行此操作并在单击按钮时执行此操作,但没有任何反应。

在我的 activity 中,我现在这样称呼片段:

    FragmentManager fm = getSupportFragmentManager();
    NewDialog newDialog = NewDialog.newInstace(userId, loc, currentId);
    newDialog.setNewClickListener(new NewDialog.OnNewClickListener() {
        @Override
        public void onCancelClicked() {
            finishAdd();
        }

        @Override
        public void onAcceptClicked() {
            ...
        }
    });
    newDialog.show(fm, "new_frag");

和片段:

public class NewDeliveryPointDialog extends DialogFragment {
    private LayoutInflater inflater;
    private ViewGroup container;

    public NewDialog(){
    }

    public static NewDialog newInstace(){
        ...
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        this.container = container;
        return inflater.inflate(R.layout.dialog_layout_1, container);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        saveButton.setOnClickListener(v -> {
                View.inflate(getContext(), R.layout.dialog_layout_2, container);
                view.invalidate();
                view.refreshDrawableState();
            }

        });
    }
}

DialogFragment 不能导航到同一对话框中的其他片段。

你基本上有这些选择:

  1. 在您的按钮上单击您关闭对话框并打开另一个对话框。但这似乎很奇怪。如果有这么多事情发生,对话可能不是最好的选择。
  2. 用另一个片段容器代替 DialogFragments 覆盖原始片段容器(基本上是 Dialog 片段为您做的)。在第二个容器中,您可以轻松导航到其他片段,并在用户完成交互后将其设置为消失。
  3. 如果Dialog中只有几个View,可以考虑将旧的设置为gone,将新的设置为visible

我认为您的代码无效,因为容器为空。方法 onCreateView 为您提供 @Nullable ViewGroup 容器,它对于 DialogFragment 为空(但对于 片段)。因此,当您调用 View.inflate(getContext(), R.layout.dialog_layout_2, container) 时,它只会在内存中创建一个视图,而不会将它附加到容器,因为它是空的。请参阅 LayoutInflater.inflate, cause View.inflate 只是此功能的便利包装器。

I dont think there is an easy way to change views inside of the same DialogFragment so what would be the best way to do this?

您可以在对话框根布局中操作子视图(添加、删除它们或更改可见性),而不是更改对话框根。

此外,我的建议是使用 recommended way 创建具有自定义布局的对话框 (onCreateDialog + setView),但如果您不想这样做,您可以将您在 onCreateView 中创建的视图引用为对话框根。

您可以尝试创建一个具有空 shell 布局的对话框片段,在其中您可以将两个不同的片段替换为 ChildFragmentManager 和常规片段事务

可以使用 activity 的视图模型在它们之间传递数据,因为它们都位于同一个 activity。

因此使用 activity 的 FragmentManager 添加 ShellDialogFragment 并在 shell 片段中 class 在 NewDialogNewDeliveryPointDialog 在你的按钮上点击监听器 ChildFragmentManager