赞
踩
问题: 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绑定。
- if (fragmentA.isAdded()) {
- getText(R.string.myString);
- }
注意:对于DialogFragment, DialogFragement.show()内部调用了FragmentTransaction.add()。所以在DialogFragement.show()之前,context是null
ref:
https://blog.csdn.net/gengbaolong/article/details/103973804
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。