我开发了一个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