美文网首页
Fragment not attached to Activi

Fragment not attached to Activi

作者: Kingsley_Wu | 来源:发表于2017-08-03 20:07 被阅读240次

问题:

java.lang.IllegalStateException: Fragment MusicNetFragment{4840349} not attached to Activity                                                                        at android.support.v4.app.Fragment.getResources(Fragment.java:646) 

原因:

在Fragment的构造方法中调用了 getResources();

getResources().getStringArray(R.array.string);

由于new Fragment构造方法时还没有与FragmentActivity 进行 attached,所以父类Fragment中找不到 (FragmentHostCallback) mHost 即为空. 所以调用getResources()时抛出了异常;

final public Resources getResources() { if(mHost==null) {

throw newIllegalStateException("Fragment "+this+" not attached to Activity");

}

returnmHost.getContext().getResources();

}

来看下源代码: 只用当Fragment与activity 产生关系时(attached)才会调用如下

FragmentActivity类 : 在成员变量中new 了一个 HostCallbacks对象,(HostCallbacks继承自FragmentHostCallback)

final FragmentController mFragments = FragmentController.createController(new HostCallbacks()); 

FragmentController类:

private FragmentController(FragmentHostCallback callbacks) {

mHost= callbacks;

}

该图片引用于: http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/1030/3641.html

解决方法: 

在onStart()方法中进行getResources()操作;

相关文章

网友评论

      本文标题:Fragment not attached to Activi

      本文链接:https://www.haomeiwen.com/subject/uoxmlxtx.html