When using Fragments
, you can think of them as being the View
and the Activity
as being the Controller
. In my personal opinion, Fragments was Google's knee jerk reaction to support tablets, and now we are stuck with them :(
I use fragments everyday, and I certainly feel your pain. When I first read about them I thought to myself, "this is really cool", but after using them, they fall short in so so many ways, but mainly because I would use them incorrectly :(
Here are some of pitfalls that I encountered...
Don't use onclick
in your fragment layout, since it's the Activity
and NOT the Fragment
that will handle the click. If you use the attribute, and later you use the fragment in another Activity
, then you'll have to remember to add the onclick
method to that Activity
as well. So, use a findViewById
and then manually attach the click handler in the fragment's onCreateView
.
When communicating with other Fragments, use the Activity
as the controller to direct the message. (Lots of examples of how do this using interfaces). The key here is that if you are running multiple fragments on a device where one fragment will communicate directly with another fragment, then you run into some odd, but predictable behavior. For example if Fragment A directly updated a View in Fragment B, but Fragment B is not visible (because you've replaced it -- consider a phone), then when Fragment B is visible, then the View
may not be updated, since the View
is recreated. So, if you update a Fragment
be sure to update the data in a fragment then update the View
portions in the onCreateView
which is called when the fragment becomes visible again (ie, you've popped the current fragment, you are now showing the previous one)
Don't build a complete application using only fragments. Instead build apps like you would normally, using Activities and then treat the Fragment
has a glorified view (which it is). ie, design the App such that you have multiple fragments and multiple Activities, and some Activities may use more than 1 fragment.
My first thought with fragments was a one where I thought it would great to just build a complete app using fragments and one activity... I eventually finished the App, but I ran into so many issues using that approach. My next approach was to use multiple fragments and multiple activities and it went much better.
Bottom line is that Fragments are great if you use them as a View
, but if you start trying to use them like Activities, then you are going to run into problems :( Think of the Activiy
-> Fragment
as the being the Controller
-> View
.
I also recommend that you read and understand the Fragment Lifecycle in addition to the Activity Lifecycle (Pro Android 4 has a great picture to represent it) and you'll save yourself hours of pain :)