1. 程式人生 > >Fragment XXX not attached to Activity

Fragment XXX not attached to Activity

上午點開專案app文章瀏覽時出現了以下錯誤:

2018-10-22 11:19:06.425 31321-31321/com.jm.fxw E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.jm.fxw, PID: 31321
    java.lang.IllegalStateException: Fragment ArticleDetailDelegate{4e8a308} not attached to Activity
        at android.support.v4.app.Fragment.getResources(Fragment.java:715)
        at com.jm.ec.main.index.article.ArticleDetailDelegate.updateZan(ArticleDetailDelegate.java:306)
        at com.jm.ec.main.index.article.ArticleDetailDelegate.handleZanResult(ArticleDetailDelegate.java:300)
        at com.jm.ec.main.index.article.ArticleDetailDelegate.lambda$cK6ng6nnI4SMTw1P3K3-br7tLeQ(ArticleDetailDelegate.java)
        at com.jm.ec.main.index.article.-$$Lambda$ArticleDetailDelegate$cK6ng6nnI4SMTw1P3K3-br7tLeQ.onSuccess(lambda)
        at com.jm.core.net.callback.RequestCallbacks.onResponse(RequestCallbacks.java:44)
        at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
        at android.os.Handler.handleCallback(Handler.java:754)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:163)
        at android.app.ActivityThread.main(ActivityThread.java:6360)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)

查看了報錯位置,定位到Drawable drawable = getResources().getDrawable(R.drawable.zan_selected);

private void updateZan() {
        TextView tvZan = newsFooter.findViewById(R.id.tv_zan);
        Drawable drawable = getResources().getDrawable(R.drawable.zan_selected);
        tvZan.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, drawable, null);
        tvZan.setCompoundDrawablePadding(5);
    }

這有可能是因為Fragment在還沒有Attach到Activity時,呼叫瞭如getResource()等,需要上下文Content的程式碼。因此在使用到上下文資源的地方加上isAdded()判斷,getResources前加上 getActivity(),如下:

private void updateZan() {
        if(isAdded()){
            TextView tvZan = newsFooter.findViewById(R.id.tv_zan);
            Drawable drawable = getActivity().getResources().getDrawable(R.drawable.zan_selected);
            tvZan.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, drawable, null);
            tvZan.setCompoundDrawablePadding(5);
        }
    }

繼續測試,未出現以上錯誤。