Skip to content

Instantly share code, notes, and snippets.

@noaht11
Last active July 11, 2016 16:33
Show Gist options
  • Save noaht11/b8278214ef5172968eaf to your computer and use it in GitHub Desktop.
Save noaht11/b8278214ef5172968eaf to your computer and use it in GitHub Desktop.
How to properly add a Fragment to an Activity so that you can handle orientation changes
private static final String TAG_MY_FRAGMENT = "myFragment";
private MyFragment mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_fragments);
if (savedInstanceState == null) {
// The Activity is NOT being re-created so we can instantiate a new Fragment
// and add it to the Activity
mFragment = new MyFragment();
getSupportFragmentManager()
.beginTransaction()
// It's almost always a good idea to use .replace instead of .add so that
// you never accidentally layer multiple Fragments on top of each other
// unless of course that's your intention
.replace(R.id.content_frame, mFragment, TAG_MY_FRAGMENT)
.commit();
} else {
// The Activity IS being re-created so we don't need to instantiate the Fragment or add it,
// but if we need a reference to it, we can use the tag we passed to .replace
mFragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(TAG_MY_FRAGMENT);
}
}
...
public void myMethod() {
// Later on in the code we can do something with the Fragment
mFragment.doSomething();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment