2014-10-28 67 views
0

我開發了一個Android應用程序,它由FragmentActivity和在選項卡更改時調用的多個片段組成。 每個片段都與一個視圖相關聯。片段的邏輯被封裝在不同的類中。這些類會進行一些複雜的計算。這些計算的結果將在片段視圖的幾個文本視圖中顯示。此外,片段 視圖包含一個停止按鈕,並且類的計算將在點擊停止按鈕時作出反應。Android:由於成員變量導致內存泄漏?

我現在的問題是如何組織對類中的這些視圖成員(文本視圖和停止按鈕)的訪問。 是否安全地將與每個文本視圖關聯的變量作爲成員變量傳遞給相應的類?這是我使用的各自的代碼。

class ClassAFragment extends Fragment 
{ 
    ClassA classA; 
    ... 

    public View onCreateView(...) 
    { 
     Button stopButton = (Button) this.getActivity().findViewById (R.id.btnStop); 
     TextView timeLabel = (TextView) this.getActivity().findViewById (R.id.mTimeLabel); 

     this.classA = new ClassA(); 
     this.classA.setAppElements(timeLabel, stopButton); 
    } 

    ... 
} 

class ClassA 
{ 
    TextView mTimeLabel; 
    Button mStopButton; 

    public void setAppElements(TextView timeLabel, Button stopButton) 
    { 
     this.mTimeLabel = timeLabel; 
     this.mStopButton = stopButton; 

     this.mStopButton.setOnClickListener (this.mStopListener); 
    } 

    private void showCurrentProgress() 
    { 
     this.mTimeLabel.setText("some text"); 
    } 

    public void stop() 
    { 
     // react upon stop button being clicked 
    } 

    OnClickListener mStopListener = new OnClickListener() 
    { 
     @Override 
     public void onClick (View v) 
     { 
      ClassA.this.stop(); 
     } 
    }; 

    ... 
} 

該代碼是否安全的內存泄漏?在官方的Android文檔中,我讀過你不應該 將綁定到App上下文的任何對象傳遞給成員變量(Handling Runtime Changes)。

回答

1

您可以使用LocalBroadcastManager或Bus(例如Otto EventBus)來通知UI(您的案例中的片段)。 LocalBroadcastManager速度更快(但是,總線,使用反射不是在ICS Android版本前分支,可能會更慢),但總線更簡單。希望能幫助到你。

P.S.永遠不要在UI片段上放置setRetainInstance(true)。

P.P.S如果你這樣做 - 確保你正確地釋放onDestroy中的視圖()

+0

非常感謝你指向我LocalBroadcastManager。我現在使用這個構造來在我的應用程序的元素之間交換消息。 – LaDude 2014-11-03 08:39:55

1

他們正在討論如果在片段中使用setRetainInstance(true);並向其傳遞對與上下文關聯的任何其他對象的引用時可能會遇到的問題。 setRetainInstance(true);意味着在活動被破壞時碎片不會被銷燬,所以如果你傳遞一個對View的引用並銷燬Activity,這將導致內存泄漏,因爲View不會被垃圾收集。