我開發了一個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)。
非常感謝你指向我LocalBroadcastManager。我現在使用這個構造來在我的應用程序的元素之間交換消息。 – LaDude 2014-11-03 08:39:55