[TUTORIAL] Working with Fragments in a ViewPager
Hi to all, it’s time to post the first android tutorial in this blog and this time I want to talk about the comunication mechanism between Fragments (you can find my other tutorials at alchemiaandroid.altervista.org).
In this tutorial we’ll focused on a communication between two Fragment (one in the role of sender and one in the role of receiver) across a FragmentActivity, that’ll work as container and channel between them.
You’ll find the project as attachment.
Difficulty level: 3/5
Terms and Documentation that you have to know:
- Fragment: it’s a piece of code and layout that works as it is inside a container
- FragmentActivity: it’s a container that can ingest fragments
- MessageLoader: in this project it’s an interface that defines a method to send a message between fragments
- ViewPager: it’s a laoyut manager that allows user to flip with his finger between “pages”
- FragmentPagerAdapter: it’s the adapter that’ll we associate to our ViewPager
We want to create a communication channel between two Fragments allowing our developer to pass information between them.
- FirstFragment: it’s our receiver; it has a TextView that contains received message and a Button to reset the view.
- SecondFragmet: it’s our sender; it has an EditText to digit our message and a Button to send it.
This goals will satisfied creating a sort of Publisher and Subscriber model between them.
- Our ViewPagerActivity eats our Fragments and choses to visualize the sender as first visible fragment
- The FirstFragment hasn’t a message in its TextView
- You need to flip, with your finger or sender button, to SecondFragment
- Here you can write a simple message
- The sent message will arrive to our FirstFragment travelling through the container
What do you think about this tutorial? It’s useful to solve your problems and/or curiosities?
See you next time,