我得到片段未附加到上下文。需要使用什么上下文?

时间:2019-10-31 13:01:58

标签: android imageview fragment

我从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。我需要在片段中使用什么上下文来设置颜色滤镜?谢谢

5 个答案:

答案 0 :(得分:4)

在您的片段中添加它:

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));

答案 1 :(得分:1)

发生此崩溃的原因是,您试图从已经与父活动分离的片段中调用getContext()。

从堆栈跟踪中可以看到,从处理程序调用了MyFragment.java第156行,这使我假设它正在执行一些后台工作,但在分离该片段时它已经完成。

对此的快速解决方案是在尝试执行修改视图的任何代码行之前检查片段是否已附加到活动。

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;
}

答案 2 :(得分:0)

尝试使用应用程序上下文来获取应用程序资源以防止IllegalStateException(未附加到上下文)

clients_macs = [client_mac_node.text for client_mac_node in xml_doc.iter('client_mac')]

with open('clients.txt', 'w') as f:
    f.write('\n'.join(clients_macs))

然后在想要获取应用程序资源的任何地方使用appContext var:

// Init global variable with the application context first:
@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    if (appContext == null)
        appContext = context.getApplicationContext();
}

答案 3 :(得分:0)

当片段尚未创建或已经被破坏时,您可能正在尝试访问ViewPager的子Fragmnet组件。您能使您的帖子更详细吗?

答案 4 :(得分:-1)

在您的片段中,可以在requireContext() / requireActivity()内使用onViewCreated而不是getContext() / getActivity()

imageView.setColorFilter(ContextCompat.getColor(requireContext(), R.color.blue));