Search code examples
androidandroid-studiokotlinandroid-fragmentsandroid-activity

Android - Activity To Fragment


I have my MainActivity where there are the movie with their poster. If I click on a poster (ImageButton) I can read the plot (TextView) that is in the Fragment. How can I connect the Activity to the Fragment?


Solution

  • I am not sure what do you want to accomplish but I wouldn't add ImageButton in the MainActivity, I think that the best approach would be that You add only FragmentContainerView in your MainActivity:

    <androidx.fragment.app.FragmentContainerView
            android:id="@+id/myFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent""
            app:layout_constraintBottom_toTopOf="parent"
            app:layout_constraintTop_toBottomOf="parent" />
    

    After that you can override onStart function in MainActivity and add:

    var fr = getFragmentManager()?.beginTransaction()
                fr?.replace(binding.myFragment, MovieFragment())
                fr?.commit()
    

    MovieFragment() should have your ImageButton so when you click on it you can easily change fragment with method above or you can add below ImageButton another FragmentContainerView to show information there.

    But if you need to fetch something from the fragment in activity than you should use ViewModel and get it in activity with:

    private val myViewModel: MyViewModel by viewModels()