首页 > 代码库 > Fragment not attached to Activity

Fragment not attached to Activity

当我点击返回按钮,返回桌面的时候,就会报错,Fragment not attached to Activity这个错误,看logcat里是因为

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.battery_full);是因为用到了getResources()这个方法,


原因是这样的Fragment在Activity中加载前就调用了或者是在Activity消失后继续调用getResources()方法,获取资源的一些方法。


怎么解决呢??


在Fragment中有 isAdded()这个方法,只需要在加载资源前进行判断即可:

if (isAdded()) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
					R.drawable.battery_full);
}


sAdded()官方解释:

isAdded()
Return true if the fragment is currently added to its activity.



Fragment not attached to Activity