仅显示一个 DialogFragment

6

我正在尝试设置一个对话框,当我的Android用户接收到推送通知时,它会弹出。下面的代码触发了对话框。我遇到的问题是,如果我的用户收到多个推送,他们将看到多个对话框弹出。

我的期望操作是只显示一个对话框,如果在当前对话框关闭之前弹出另一个对话框,则应销毁当前对话框,然后显示新的对话框。

public abstract class BaseActivity extends ActionBarActivity {
  public void showShiftsDialog(String time) {
      String DIALOG_ALERT = "dialog_alert";

      FragmentTransaction transaction = getFragmentManager().beginTransaction();
      android.app.Fragment prev = getFragmentManager().findFragmentByTag(DIALOG_ALERT);

      if (prev != null) transaction.remove(prev);
      transaction.addToBackStack(null);

      // create and show the dialog
      DialogFragment newFragment = ShiftsDialogFragment.newInstance(time);
      newFragment.show(getSupportFragmentManager().beginTransaction(), DIALOG_ALERT);
  }
}

我尝试使用来自Android文档的代码(http://developer.android.com/reference/android/app/DialogFragment.html)。调试时,prev始终为空。

据我理解,似乎是我将DialogFragment附加到SupportFragmentManager:

newFragment.show(getSupportFragmentManager().beginTransaction(), DIALOG_ALERT);

当我尝试检查是否存在当前的DialogFragment时,我是从FragmentManager中进行检查:

 android.app.Fragment prev = getFragmentManager().findFragmentByTag(DIALOG_ALERT);

如果我尝试更改代码以尝试从SupportFragmentManager中获取它,我会得到一个不兼容类型错误,因为它期望android.app.Fragment,但我却返回了一个android.support.v4.app.Fragment

android.app.Fragment prev = getSupportFragmentManager().findFragmentByTag(DIALOG_ALERT);

我该如何管理我的DialogFragment,以便在任何给定时间只显示一个?
工作方案
public void showShiftsDialog(String time) {
    String DIALOG_ALERT = "dialog_alert";

    android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    android.support.v4.app.Fragment prev = getSupportFragmentManager().findFragmentByTag(DIALOG_ALERT);

    if (prev != null){
        DialogFragment df = (DialogFragment) prev;
        df.dismiss();
        transaction.remove(prev);
    }

    transaction.addToBackStack(null);

    // create and show the dialog
    DialogFragment newFragment = ShiftsDialogFragment.newInstance(time);
    newFragment.show(getSupportFragmentManager().beginTransaction(), DIALOG_ALERT);
}

你在哪里添加第一个对话框?同时,只使用android.support.v4.app.Fragment和getSupportFragmentManager()方法。 - Sam Dozor
1
"transaction.addToBackStack(null);" 这行代码是做什么用的? - Lars
1个回答

8
您的问题似乎是与 DialogFragment 不兼容有关。如果 ShiftsDialogFragment 是 android.support.v4.app.DialogFragment 的子类,则可以使用:
android.support.v4.app.Fragment prev = getSupportFragmentManager().findFragmentByTag(DIALOG_ALERT);

太棒了,这解决了错误,并且当已经打开对话框时,prev 似乎不再为空。但是,它并没有关闭对话框。你知道我怎么才能关闭对话框吗? - Huy
没关系,我已经想通了。会将它加入到我的解决方案中。 - Huy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接