最近,我在android studio中启动了一个新项目,遇到一个我无法真正发现或看到问题的错误,我的应用程序碰到getSupportFragmentManager()行时崩溃了。我在TimePickerFragment旁边使用它
我尝试谷歌搜索不同的事物,并尝试以不同的方式实现这一目标
ButtonListeners类
import android.app.TimePickerDialog;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
public class ButtonListeners extends FragmentActivity implements
View.OnClickListener, TimePickerDialog.OnTimeSetListener {
@Override
public void onClick(View buttons) {
switch (buttons.getId()){
case R.id.button1:
break;
case R.id.button2:
DialogFragment timePicker = new TimePickerFragment();
**FragmentManager manager = getSupportFragmentManager();** //<< error here
timePicker.show(manager,"timepicker");
}
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//do something
}
}
TimePickerFragment类
public class TimePickerFragment extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(), hour, minute, DateFormat.is24HourFormat(getActivity()));
}
}
LogCat
2019-06-18 16:29:24.449 25857-25857/com.example.calendar E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.calendar, PID: 25857
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:2114)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:683)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:637)
at android.support.v4.app.DialogFragment.show(DialogFragment.java:144)
at com.example.calendar.ButtonListeners.onClick(ButtonListeners.java:28)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
答案 0 :(得分:0)
尝试使用getFragmentManager()代替getSupportFragmentManager()。 还有第二个选项,使用getActivity()。getSupportFragmentManager();