Huy*_*Huy 4 android android-fragments android-dialogfragment
我正在尝试设置一个对话框片段,当我的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);
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用Android文档中的代码(http://developer.android.com/reference/android/app/DialogFragment.html).调试时,它看起来prev总是为null.
根据我的理解,看起来我将DialogFragment附加到SupportFragmentManager:
newFragment.show(getSupportFragmentManager().beginTransaction(), DIALOG_ALERT);
Run Code Online (Sandbox Code Playgroud)
当我尝试检查是否有任何当前的DialogFragment时,我正在检查FragmentManager:
android.app.Fragment prev = getFragmentManager().findFragmentByTag(DIALOG_ALERT);
Run Code Online (Sandbox Code Playgroud)
如果我尝试更改代码以尝试从SupportFragmentManager获取它,我会得到一个不兼容的类型错误,它会在期待android.app.Fragment,但我返回一个android.support.v4.app.Fragment:
android.app.Fragment prev = getSupportFragmentManager().findFragmentByTag(DIALOG_ALERT);
Run Code Online (Sandbox Code Playgroud)
如何管理我的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);
}
Run Code Online (Sandbox Code Playgroud)
你的问题似乎是不相容的DialogFragment.如果ShiftsDialogFragment是android.support.v4.app.DialogFragment你可以使用的子类
android.support.v4.app.Fragment prev = getSupportFragmentManager().findFragmentByTag(DIALOG_ALERT);
Run Code Online (Sandbox Code Playgroud)