2014-10-28 69 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不会被垃圾收集。