gpt4 book ai didi

android - Activity 被杀死后恢复了多个 DialogFragment

转载 作者:搜寻专家 更新时间:2023-11-01 08:01:10 28 4
gpt4 key购买 nike

我有 1 个 Activity 显示 1 个 DialogFragment,我使用 setAlwaysFinish 应用强制 Activity 在 onPause 后被杀死。

在暂停和恢复 Activity 后,我有时会显示 23 相同的 DialogFragment。有人知道如何防止这种情况吗?

注意:我离开了 Activity,但 Dialog 仍然显示。在多次尝试使用 setAlwaysFinish 后,该错误被发现。

代码: Activity

package com.example.testdialog;
import java.util.Calendar;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;

public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void showDialog(View v) {
Calendar today = Calendar.getInstance();
DialogFragment d = DateDialog.newInstance(today.get(Calendar.DAY_OF_MONTH), today.get(Calendar.MONTH), today.get(Calendar.YEAR));
d.show(getSupportFragmentManager(), "mydialog");
}
}

代码:DialogFragment

package com.example.testdialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;

public class DateDialog extends DialogFragment implements OnDateSetListener {
public static final String TAG = "datepicker";
public static final int SEARCH_FLIGHT = 0;
public static final int PASSENGER = 1;

static DateDialog newInstance(int day, int month, int year) {
DateDialog d = new DateDialog();
Bundle bun = new Bundle();
bun.putInt("day", day);
bun.putInt("month", month);
bun.putInt("year", year);
d.setArguments(bun);
return d;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle bun = getArguments();
int year = bun.getInt("year");
int month = bun.getInt("month");
int day = bun.getInt("day");

DatePickerDialog d = new DatePickerDialog(getActivity(), this, year, month, day);
d.setButton(DialogInterface.BUTTON_POSITIVE, "OK", d);
d.setTitle("my dialog");
return d;
}

@Override
public void onDestroyView() {
Dialog d = getDialog();
if (d != null && getRetainInstance())
d.setDismissMessage(null);
super.onDestroyView();
}
}

最佳答案

你可以在你的dialogfragment中使用这个来阻止它:

@Override
public void show(FragmentManager manager, String tag) {
if (tag != null && tag.equals("FRAGMENT_TAG_MAX_ONE_INSTANCE")) {
// we do not show it twice
if (manager.findFragmentByTag(tag) == null) {
super.show(manager, tag);
}
} else {
super.show(manager, tag);
}
}

和改变:

d.show(getSupportFragmentManager(), "FRAGMENT_TAG_MAX_ONE_INSTANCE");

关于android - Activity 被杀死后恢复了多个 DialogFragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21042539/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com