我从Firebase Crashlytics得到异常
Fatal Exception: java.lang.IllegalStateException: Fragment MyFragment{122418b (05b123e6-aa8d-4de4-8f7e-49c95018234b)} not attached to a context.
at androidx.fragment.app.Fragment.requireContext(Fragment.java:774)
at androidx.fragment.app.Fragment.getResources(Fragment.java:838)
at com.timskiy.pregnancy.fragments.MyFragment$1$1.run(MyFragment.java:156)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
片段中的错误行
imageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.blue));
也尝试过
imageView.setColorFilter(getResources().getColor(R.color.blue));
我在Activity和FragmentStatePagerAdapter中使用viewPager。我需要在fragment to setColorFilter中使用什么上下文?Thx
发布于 2019-10-31 13:08:28
将以下内容添加到您的片段中:
private Context mContext;
@Override
public void onAttach(Context context) {
super.onAttach(activity);
mContext = context;
}
@Override
public void onDetach() {
super.onDetach();
mContext = null;
}
在你的图像视图中
imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.blue));
发布于 2019-10-31 13:53:58
尝试使用应用程序上下文获取应用程序资源以防止IllegalStateException (未附加到上下文)
// Init global variable with the application context first:
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (appContext == null)
appContext = context.getApplicationContext();
}
然后在您想要获取应用程序资源的任何地方使用appContext变量,例如:
imageView.setColorFilter(ContextCompat.getColor(appContext, R.color.blue));
发布于 2020-08-04 13:27:54
之所以会出现这种崩溃,是因为您试图从已从父活动分离的片段中调用getContext()。
从堆栈跟踪看,似乎有一个处理程序对MyFragment.java行156的调用,这使我认为它是一些后台工作正在发生,但它在片段被分离时完成。
解决这个问题的一个快速方法是,在尝试执行修改视图的任何代码行之前,检查片段是否附加到activity。
if (isAttachedToActivity()){
imageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.blue));
}
或
if (isAttachedToActivity()){
imageView.setColorFilter(getResources().getColor(R.color.blue));
}
isAttachedToActivity()如下所示:
public boolean isAttachedToActivity() {
boolean attached = isVisible() && getActivity() != null;
return attached;
}
https://stackoverflow.com/questions/58643962
复制相似问题