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

Tim*_*Web 8 android fragment imageview

我从 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)
Run Code Online (Sandbox Code Playgroud)

片段中的错误行

imageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.blue));
Run Code Online (Sandbox Code Playgroud)

也试过

imageView.setColorFilter(getResources().getColor(R.color.blue));
Run Code Online (Sandbox Code Playgroud)

我在 Activity 和 FragmentStatePagerAdapter 中使用 viewPager。我需要在片段中使用什么上下文来 setColorFilter?谢谢

Zee*_*han 9

在你的片段中添加这个:

private Context mContext;    

@Override
public void onAttach(Context context) {
    super.onAttach(activity);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    mContext = null;
}
Run Code Online (Sandbox Code Playgroud)

在你的图像视图中

imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.blue));
Run Code Online (Sandbox Code Playgroud)


kev*_*kev 5

您遇到此崩溃是因为您尝试从已与父 Activity 分离的片段调用 getContext() 。

从堆栈跟踪来看,处理程序似乎调用了 MyFragment.java 第 156 行,这使我假设它正在发生一些后台工作,但当片段被分离时它就完成了。

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

if (isAttachedToActivity()){
  imageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.blue));
}
Run Code Online (Sandbox Code Playgroud)

或者

if (isAttachedToActivity()){
  imageView.setColorFilter(getResources().getColor(R.color.blue));
}
Run Code Online (Sandbox Code Playgroud)

isAttachedToActivity() 看起来像这样:

public boolean isAttachedToActivity() {
    boolean attached = isVisible() && getActivity() != null;
    return attached;
}
Run Code Online (Sandbox Code Playgroud)


Md.*_*man -1

在您的片段中,使用requireContext() / requireActivity()insideonViewCreated而不是是安全的getContext() / getActivity()

imageView.setColorFilter(ContextCompat.getColor(requireContext(), R.color.blue));
Run Code Online (Sandbox Code Playgroud)

  • `requireContext` 和 `requireActivity` 也会抛出异常 (2认同)