【发布时间】:2014-12-02 03:02:47
【问题描述】:
我正在尝试设置当我的 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() 方法。
-
什么是“transaction.addToBackStack(null);”行吗?
标签: android android-fragments android-dialogfragment