Android – Why not to use static for View fields in your Activity or Fragments by Lars Vogel

Your should not use static for defining fields for Views in your Android application.

Then creating a View, the LayoutInflater (used in setContentView(R.layout.ID)) uses the current Context (of the Activity) and pass it to the inflated Views. A reference to the given Context is always kept by the View class and can be retrieved via the getContext() method.

As a consequence, keeping a static reference on a View means that your Activity keeps a reference on your View which keeps a reference on the activity instance. This is what leads to the leak.

Thanks to Cyril Mottier for explaining that in G+.

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Android. Bookmark the permalink.