Skip to content

Instantly share code, notes, and snippets.

@jobinlawrance
Created November 2, 2020 06:58
Show Gist options
  • Save jobinlawrance/fed01d345e703ddef366b47f07d1d1dd to your computer and use it in GitHub Desktop.
Save jobinlawrance/fed01d345e703ddef366b47f07d1d1dd to your computer and use it in GitHub Desktop.
class MainActivity : AppCompatActivity() {
val mainFragment by fragmentByTagOrNew(MainFragment.TAG) {
MainFragment().withArgs {
putString(MainFragment.KEY_TEXT, "Now this won't crash")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
if(!mainFragment.isAdded()) {
supportFragmentManager.beginTransaction()
.add(R.layout.fragmentContainerView, mainFragment)
.commit()
}
}
}
class MainFragment : Fragment() {
private val textToDisplay by argument<String>(KEY_TEXT)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
textToDisplay = requireArguments().getString(KEY_TEXT)
// Logic related to using $textToDisplay
}
companion object {
const val KEY_TEXT = "KeyText"
const val TAG = "MainFragment"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment