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?
Question posted in Android Studio
The official documentation can be found here.
The official documentation can be found here.
2
Answers
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.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:
After that you can override onStart function in MainActivity and add:
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: