Skip to content

Instantly share code, notes, and snippets.

@jpetitto
Created August 19, 2015 16:12
Show Gist options
  • Save jpetitto/62b487cd046ee80ef28d to your computer and use it in GitHub Desktop.
Save jpetitto/62b487cd046ee80ef28d to your computer and use it in GitHub Desktop.
Save Fragment state across config changes
public class MainActivity extends AppCompatActivity {
private Fragment savedFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
savedFragment = getSupportFragmentManager().getFragment(savedInstanceState, "content");
} else {
savedFragment = new UserInfoFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, savedFragment)
.commit();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "content", savedFragment);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment