当前位置:   article > 正文

IllegalStateException: Fragment not attached to a context.

fragment not attached to a context.

问题: java.lang.IllegalStateException: Fragment <...> not attached to a context.

根源: fragment 没有和 activity绑定, context为空.

参考: Fragment.java

@NonNull
public final Context requireContext() {
    Context context = getContext();
    if (context == null) {
        throw new IllegalStateException("Fragment " + this + " not attached to a context.");
    }
    return context;
}

解决办法: 可以在fragment内部,使用isAdded()来判断是否fragment和activity绑定。

  1. if (fragmentA.isAdded()) {
  2. getText(R.string.myString);
  3. }

注意:对于DialogFragment, DialogFragement.show()内部调用了FragmentTransaction.add()。所以在DialogFragement.show()之前,context是null

ref: 

https://blog.csdn.net/gengbaolong/article/details/103973804

https://blog.csdn.net/u012264122/article/details/50503886

https://www.jianshu.com/p/9e1dc12a1e65

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/253178
推荐阅读
相关标签
  

闽ICP备14008679号