I need to pre load a complex layout so I can show the activity more quickly the first time:
LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
SlowActivity.cachedView = inflater.inflate(R.layout.activity_layout, null, false);
when SlowActivity starts…
public static View cachedView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(this.cachedView);
}
}
I can’t find where I read it but some one says that I’m doing a memory leak using a stati variable to store inflated layout.
Why?
Maybe I need to release some resource when activity is destroyed (never, it’s always put on the background…)
that’s because the layout , just like all views , has a reference to the activity that holds it.
so, after the activity was closed and should be releaseed , the static variable holds a reference to a view that references to the this activity, so the app takes more memory than it should .
views are not the only variables that you should try to avoid caching using static variables . an example for this is drawables , as seen here .