我正在尝试设置一个对话框,当我的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);
}