I'm writing an app where I'm using fragments, and I'm seeing a really confusing behavior in my DDMS heap dumps: When I initially run my application, let's say there are a couple of fragments in the stack:
HomeFragment: 1
WelcomeFragment: 1
SignInFragment: 1
CreateAcctFragment: 1
The immediate dominator for each of these is .
Th开发者_StackOverflow中文版en I rotate the screen. I now get:
HomeFragment: 2
WelcomeFragment: 2
SignInFragment: 2
CreateAcctFragment: 2
Now the immediate dominators for each instance are for one and android.support.v4.app.FragmentManagerImpl
for the other.
I initially thought I had a memory leak, that one of my fragments was not being garbage collected, as that had happened to me before. However, in that case every time I rotated the screen I added one more instance of each. Now no matter how many times I rotate the screen, I "only" see 2 instances of each.
Any thoughts/suggestions?
You should only instantiate the fragments if your activity onCreate() method is not passed a bundle. The android framework will instantiate them for you if a bundle is passed to onCreate().
This is the example of Activity.onCreate from fragment docs: http://developer.android.com/guide/topics/fundamentals/fragments.html
public static class DetailsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
精彩评论