在利用Fragment做開發的時候,偶爾或者是少數情況下報錯:Fragment XXFragment not attached to Activity,這有可能是因爲Fragment在還沒有Attach到Activity時,調用瞭如getResource()等,需要上下文Content的代碼。因此在使用到上下文資源的地方加上:
if(isAdded()){
getResources().getString(R.string.app_name);
}
參考stackoverflow:http://stackoverflow.com/questions/10919240/fragment-myfragment-not-attached-to-activity
注:本人遇到這個問題也是在AsyncTask中使用了getResource,加上上述代碼完美解決問題。