在我正在开发的应用程序中我动态添加片段,现在我想删除它们但我不能,应用程序崩溃。非常感谢您的帮助。 这是我的代码
这里声明了我使用的东西
static int alarmsAmount = 0;
public android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
public AlarmFragment[] alarmFragment = new AlarmFragment[7];
以下是我添加片段的方法
alarmFragment[getAlarmsAmount()] = new AlarmFragment();
alarmFragment[getAlarmsAmount()].setAlarmNumber(getAlarmsAmount());
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.alarmListContainer, alarmFragment[getAlarmsAmount()],Integer.toString(getAlarmsAmount()));
fragmentTransaction.commit();
setAlarmsAmount(getAlarmsAmount() + 1);
现在问题本身
public void removeAlarm(int alarmNumber) {
Log.d("informatione", Integer.toString(alarmNumber));
getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentByTag(Integer.toString(alarmNumber))).commit();
}
错误日志
11-03 01:33:22.634 12942-12942/com.rggmiranda.appE/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Activity has been destroyed
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1333)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.app.BackStackRecord.commit(BackStackRecord.java:574)
at com.rggmiranda.app.Alarms.removeAlarm(Alarms.java:66)
at com.rggmiranda.app.AlarmSettings$1.onClick(AlarmSettings.java:30)
at android.view.View.performClick(View.java:4340)
at android.view.View$PerformClick.run(View.java:17642)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5185)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564)
at dalvik.system.NativeStart.main(Native Method)
日志指向getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentByTag(Integer.toString(alarmNumber))).commit();
答案 0 :(得分:0)
在顶部,您使用的是getSupportFragmentManager()
,但在删除时,您使用的是getFragmentManager()
。确保在所有地方都使用getSupportFragmentManager()
。