Skip to content

Instantly share code, notes, and snippets.

@jobinlawrance
Last active December 13, 2020 10:16
Show Gist options
  • Save jobinlawrance/55ac79dde903f0186303f256b3dd774d to your computer and use it in GitHub Desktop.
Save jobinlawrance/55ac79dde903f0186303f256b3dd774d to your computer and use it in GitHub Desktop.
class MainActivity : AppCompatActivity() {
val bundle = Bundle().apply {
putString(MainFragment.KEY_TEXT, "Now this won't crash")
}
val mainFragment = MainFragment().apply {
arguements = bundle
}
override fun onCreate(savedInstanceState: Bundle?) {
// the usual stuff
if(savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.add(R.layout.fragmentContainerView, mainFragment)
.commit()
}
}
}
class MainFragment : Fragment() {
lateinit var textToDisplay: String
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
textToDisplay = requireArguments().getString(KEY_TEXT)
// Logic related to using $textToDisplay
}
companion object {
const val KEY_TEXT = "KeyText"
}
}
@Zhuinden
Copy link

Might want to add an if(savedInstanceState == null) {} check around the FragmentTransaction, otherwise this snippet would result in overlapping fragments after process death.

@jobinlawrance
Copy link
Author

Yes, thank you Gabor, I've updated the gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment