【问题标题】:Is it possible to launch a dialogfragment from a dialogfragment in android是否可以从android中的对话框片段启动对话框片段
【发布时间】:2025-12-24 10:50:07
【问题描述】:

我有一个场景,我想通过在已打开的对话框片段中单击按钮来打开一个对话框片段。我希望原件保持打开状态并在其顶部打开新的,或者隐藏原件,然后在第二个对话框片段被关闭时重新打开它。只是想知道这是否可行,然后再尝试这样做,可能会浪费我的时间。谁能给点建议?

【问题讨论】:

  • 作为参考,如果其他人正在尝试这个,它似乎是不可能的,或者比从活动中调用对话框片段更复杂。我遇到的问题与对话框片段中的 onAttach 方法有关。此时的上下文与原始调用活动有关,而不是对话片段。这意味着活动需要实现接口而不是第一个对话框片段。到目前为止,我不确定这是否会破坏逻辑。当我弄清楚这一点时,我会发布更多内容,希望对其他人有用。
  • 此代码是引发错误的地方,正是在这一点上,初始活动被引用为需要实现第二个对话框片段的接口。 code@Override public void onAttach(Context context) { super.onAttach(context);如果(OnColourPickerFragmentInteractionListener 的上下文实例) { mListener = (OnColourPickerFragmentInteractionListener) 上下文; } else { throw new RuntimeException(context.toString() + " 必须实现 OnFragmentInteractionListener"); } } code

标签: java android dialogfragment


【解决方案1】:

从上面的 cmets 开始,我发现以下似乎可行(尽管尚未实现任何逻辑,但在测试手机上编译和运行)。我用下面的代码替换了上面的onAttach方法。

    @Override
 public void onAttach(Context context) {
    super.onAttach(context);

    TextPropertiesDialogFragment prev = (TextPropertiesDialogFragment) getFragmentManager().findFragmentByTag("TextPropertiesDialogFragment");
    if (prev != null) {
        if (prev instanceof OnColourPickerFragmentInteractionListener) {
            mListener = (OnColourPickerFragmentInteractionListener) prev;
        } else {
            throw new RuntimeException(prev.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }
 }

作为参考,此 onAttach 方法位于名为 OnColourPickerDialogFragment 的第二个对话框片段中。 TextPropertiesDialogFragment 是从活动中调用的第一个对话框片段。为了完整起见,我在下面包含了侦听器和接口的定义。

public class TextPropertiesDialogFragment extends DialogFragment implements View.OnClickListener, ColourPickerDialogFragment.OnColourPickerFragmentInteractionListener{

    public void colourPickerCallBackMethod(Bundle bundle){
    //Do some work here
}
//........
}

public class ColourPickerDialogFragment extends DialogFragment implements View.OnClickListener {

private View topLevelFragmentView;
private OnColourPickerFragmentInteractionListener mListener;
private Bundle callBackBundle;

public interface OnColourPickerFragmentInteractionListener{
    void colourPickerCallBackMethod(Bundle callBackBundle);
}
//......
}

【讨论】: