问题:
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()操作;