android 片段中的 IllegalStateException 错误
IllegalStateException error in android fragment
我在片段中使用 CountDownTimer
有时 onFinish() 会抛出错误
附上错误信息和错误代码
public void onFinish()
{
btnTimerStart.setText(getString(R.string.btn_restart));
timer_display.setTextSize(45);
timer_display.setText(getString(R.string.btn_complete));
}
java.lang.IllegalStateException:
at android.support.v4.app.Fragment.requireContext (Fragment.java:696)
at android.support.v4.app.Fragment.getResources (Fragment.java:760)
at android.support.v4.app.Fragment.getString (Fragment.java:782)
at com.sinwho.timer.TimerFragment.onFinish (TimerFragment.java:751)
at android.os.CountDownTimer.handleMessage (CountDownTimer.java:127)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:214)
at android.app.ActivityThread.main (ActivityThread.java:7050)
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:965)
问题是您的 getString()
方法无法获取 context
。使用 getActivity()
为他们提供上下文。试试这个:
public void onFinish()
{
btnTimerStart.setText(getActivity().getString(R.string.btn_restart));
timer_display.setTextSize(45);
timer_display.setText(getActivity().getString(R.string.btn_complete));
}
希望你的问题得到解决。
我在片段中使用 CountDownTimer 有时 onFinish() 会抛出错误
附上错误信息和错误代码
public void onFinish()
{
btnTimerStart.setText(getString(R.string.btn_restart));
timer_display.setTextSize(45);
timer_display.setText(getString(R.string.btn_complete));
}
java.lang.IllegalStateException:
at android.support.v4.app.Fragment.requireContext (Fragment.java:696)
at android.support.v4.app.Fragment.getResources (Fragment.java:760)
at android.support.v4.app.Fragment.getString (Fragment.java:782)
at com.sinwho.timer.TimerFragment.onFinish (TimerFragment.java:751)
at android.os.CountDownTimer.handleMessage (CountDownTimer.java:127)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:214)
at android.app.ActivityThread.main (ActivityThread.java:7050)
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:965)
问题是您的 getString()
方法无法获取 context
。使用 getActivity()
为他们提供上下文。试试这个:
public void onFinish()
{
btnTimerStart.setText(getActivity().getString(R.string.btn_restart));
timer_display.setTextSize(45);
timer_display.setText(getActivity().getString(R.string.btn_complete));
}
希望你的问题得到解决。