skip to Main Content

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?

2

Answers


  1. You can get the active/attach fragment instance in your MainActivity. You can either declare that textview public or you can have backing field. When the button is pressed you can get the active instance of fragment and get the textView text.

    Login or Signup to reply.
  2. 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()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search