Skip to content

Fragment display different content

Can I make a Fragment to display different content depending on what was selected in the previous screen.

For example: I create Fragment with ImageView and TextView. In MainActivity I click Button1 and the Fragment opens and shows some content, and if I click Button2 the same Fragment opens but different content is displayed. Is it possible to do this?

Answer

Case 1: If the fragment instance is not retained/reused (for example, fragment dialog), we just need to bind flag/content via arguments when creating that fragment

fun createAFragment(flag: Int): Fragment {
    val fragment = AFragment()
    fragment.arguments = Bundle().apply { putString("keyFlag", flag) }
    return fragment
}

Inside AFragment’s onViewCreated(), we can read the flag value from arguments bundle and bind equivalent data into image view and text view. We can also bind the image resource and text to the fragment via the arguments too (see Bundle)

We can apply this approach for fragments on ViewPager too.

Case 2: The fragment instance is retained, for example, two fragments on an activity, 1 controls the another. In this case, we should use view model to share data between fragments and activity, live data for notifying data change.

This codelab might be helpful for learning about ViewModel and LiveData: https://developer.android.com/codelabs/kotlin-android-training-live-data