Will this cause memory leaks?
Will the following code cause a memory leak? Essentially I sw开发者_开发问答itch between various layouts in my application using setContentView(), and I have member variables of my activity that maintain references to various views (buttons/textviews...) on the layouts.
Am I correct in thinking that if the activity class has a reference to a button and then changes layouts the layout wont be garbage collected because it will still hold a button reference? If this is the case, can I just null the button variable before changing layouts?
Thanks.
public class MyApp extends Activity {
private Button startBtn;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set main layout
setContentView(R.layout.main);
startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
doStart();
}
});
}
private void doStart()
{
// Change to starting screen layout
setContentView(R.layout.begin);
/// .. Work with more views here and change layouts in a bit .. //
}
}
You will want to set the button to null before changing any layouts.
I don't believe that should cause a memory leak. Changing the layout doesn't destroy the activity, so the activity still has control over the bound references. Once the activity is destroyed, all the memory should be cleared up. Also, you might want to think about using separate activities if you're switching layouts that much.
Views of R.layout.main (that you initialy assign in OnCreate) will not become garbage as long as you hold startBtn reference OR as long as your activity's instance is alive. Either way it doesn't look like a potential memory leak. Just make sure to release references to views when setting new layout. Yet another thing to consider is to use WeakReference to wrap references to views of your layout (that's for complex designs). This way, as soon as your layout is no longer attached to activity (no strong references to views), all views can become a garbege even though you are referencing them via WeakReference.
精彩评论