How to call activity from another fragment.? - android

I already know how to make a fragment in Android. I want to open another activity in the same fragment on a button click event. The button is inside a fragment class.
How do I do that?

There are two possibilities depending on what you need:
Fragment Receive Result that demonstrates starting a new Activity from a Fragment, and receiving a result back from it.
setTargetFragment may be used, for example, if this fragment is being started by another, and when done wants to give a result back to the first. An example is available here

All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
Here are some tutorials with example
http://mobile.tutsplus.com/tutorials/android/android-sdk-using-fragments/
http://developer.android.com/training/basics/fragments/communicating.html
EDIT: April 2013
I like #AlexLockwood's comment.
In the case that one fragment starts another fragment, it's fine to just use setTargetFragment(Fragment, int) and communicate with it directly by calling getTargetFragment(). Communicating with Fragments through the activity is usually a good idea because it keeps your fragments loosely coupled from one another.

Related

Fragment implementation - Using google's document as an example

I am reading google developer's article on Fragment implementation. I am stuck at one point in the session "Creating event callbacks to the activity".
It says that when Fragment A, which contains a list of articles' title, wants to communicate with Article Fragment, which shows the content of the article, Fragment A should implement an interface OnArticleSelectedListener. A listener is set in the activity hosting the two fragments, and the listener will send information to Article Fragment.
My problem is that, why don't we simply implement an interface in Article Fragment listening to Fragment A's selection? I know there must be a reason, but I just don't get it.
My Attempt:
Is it because we cannot find a reference to Article Fragment in Fragment A? We could only find the reference of Article Fragment from the hosting activity.
Many Thx.
Fragments can not communicate with each other. Activity is not only a Host but also acts as a middle man between two or more fragments.
(taken from developer.android.com)
Although a Fragment is implemented as an object that's independent from an Activity and can be used inside multiple activities, a given instance of a fragment is directly tied to the activity that contains it.
In some cases, you might need a fragment to share events with the activity. A good way to do that is to define a callback interface inside the fragment and require that the host activity implement it. When the activity receives a callback through the interface, it can share the information with other fragments in the layout as necessary.

What is the difference creating event callback or the activity itself within a fragment?

Lets say I will be using several fragments(Action1Fragment, Action2Fragment etc.) within an activity(ActionActivity). I want to access some elements of activity object, or call some methods of ActionActivity. It is generally offered to create a event callback . What if I keep a reference to ActionActivity within Action1Fragment instead of keeping a reference to CallBackInterface which is actually implemented by ActionActivity since I will be using these fragments only within a particular activity.
I am kinda confused by the idea that Activity might be dead while reference of interface might still be alive(it sounds ridiculous when I read it again but it is OK if I managed to explain myself).
The Android Developer tutorials recommend that you use a callback interface on your fragments. The activity that hosts the fragment must implement the callback interface. The fragment does getActivity() and casts it to the callback interface, and then makes the callback.
This is the recommended way to promote a more modular design. It would not matter if your fragments will only ever work inside one activity. But if you want to make more generic fragments that could be used by different activities, then the above design pattern starts to become useful. (For example: a telephones fragment inside an person fragment and a company fragment.)
Suppose you do it the other way: the fragment does getActivity() and casts it to PersonActivity. The fragment then has access to all the public methods of PersonActivity. But this design pattern becomes much more ugly when you need the other activity to also use the fragment. The fragment would then have to be changed to first try and cast to PersonActivity, and if that throws, try the CompanyActivity.
The recommended design pattern basically gives you a way to make an activity compatible with the fragment instead of vice versa. The fragment only knows about the callback interface and not about any of the activities itself. The activities do know about the fragment because they implement the callback interface but they already knew about it because they constructed and initialized an instance of it.
Does that make sense?

Android best practices for Fragment to Activity communications

I am new to Android Fragment and trying to learn Fragment to Activity communications.
What is the better approach(best practice) in Android for Fragment to Activity communication?
Lets say I have FragmentA and ActivityA.
After my screen popups FragmentA, I would like to perform somemethod(probably UI related) in ActivityA
Here are two(pattern) possible
Solutions:
In FragmentA getActivity and cast the Activity to ActivityA and then call somemethod.
In FragmentA create an interface callback and then implement that callback in ActivityA. Then on the callback, call somemethod.
Which pattern is more common/perfer in Android development and why. Or do you have an even better way to communicate from fragment to activity in Android to share with me?
Any comments, opinions, and suggestions is highly appreciated and welcome. ^^ .
The second solution is the preferred one, because it allows your fragment to be more independent of its hosting activity.
If in the future you decide to put your fragment on a different activity, there are no changes needed on the fragment, and you will only need to implement the interface on your activity.
I'll add a third solution which is using an event bus (Otto for instance), which also works, although some might argue that it makes your code a little less readable.
First method will be a bad practice. Second method will work fine but your fragment is going to be tightly coupled with your activity.
There is one more better approach is to use some event bus library like otto
Using this you can communicate effectively with loose coupling in your activity & fragment.
Your second approach is more flexible. You might not see a huge benefit in one activity and one fragment case. If you have to use the same fragment in another activity, it will most likely break by casting your activity like that. That said, there is nothing wrong with the first approach, but it is just a little restricted.
First pattern is best when your fragment is used only by one activity.
Second approach is needed if you want your fragment to communicate with some other objects not the activity that hosts fragment. If you always want to communicate with hosting activity callback is not needed. Just create an interface and implement it on as many activities as needed. Then in your fragment cast activity returned by getActivity().
MyInterface myInteface = (MyInterface) getActivity();
myinterface.somemethod();
You can even check if activity implements needed interface(s) etc.
The interface approach works fine and is more flexible in so far as it doesn't tie your fragment to the activity directly. One thing you should also consider is how much work the activity might need to do, that is it may end up managing several fragments. This has a tendency to lead to 'fat fragments' as my question here asked when I started using them

Android Fragments: how do I save and pass data back to parent activity once the user closes the current activity?

I have a SearchFragment and a PersonFragment which are hosted by different FragmentActivitys
The user will navigate from the SearchFragment to the PersonFragment. When the user is done with the PersonFragment (such as when they press the back button), I would like to send data back to SearchFragment so it can update its UI with any changes the user made while in PersonFragment.
I read the best way to do this is in the Activity's finish() method. However, since I'm using fragments I'm not sure how to accomplish this.
You first communicate from PersonFragment to the associated activity using interface as a callback.
Then you can use intent to pass values between activities. From activity you can communicate to SearchFragment.
http://developer.android.com/training/basics/fragments/communicating.html
According to the tutorial on the Android developers site (link), you should declare a listener interface in your PersonFragment, implement it in your FragmentActivity and in that implementation, update your SearchFragment's UI.
Edit: Another approach would be to use LocalBroadcastManager, if you can package your relevant data in an Intent, this approach uses a bit less boilerplate code.
you dont need it, all you need to do is some ContentObserver that notifies you about the content changes, see ContentResolver and its methods: registerContentObserver() and notifyChange()
Ended up using EventBus for this

Communication among fragment and activity

I'm implementing fragments in my app. Referring to this documentation,
there is written I should use getActivity() to access activity methods but also (in the next paragraph) I should declare an interface in the fragment and let activity implement it.
Now, the second way is used for callback methods like events, but I can also use getActivity().onSomeEventHappened(), can't I?
Could someone explain me the differences? Because I cannot see differences among them.
There is no difference in the end result if you know that getActivity() will always return the type of Activity you expect.
However using interfaces is a good practice because it decouples your Fragments from a particular implementation of an Activity. So later on in the future if you decide to use your fragments with a different activity, all you have to do is have that activity implement your fragments Interface to be alerted of any fragment events.
You should always strive to have decoupled components if you want an application that is easy to extend without side effects.
You can not always simply call getActivity().onSomeEventHappened(). Just imagine this case: You have two fragments, one with ListView and other which shows image based on listItem selected. In second fragment you cannot just call getActivity().onListItemClicked(), because your activity has no such method, but if activity implements interface and catches those event from the first fragment, then you are able to pass info about event to the second fragment and how the right image.

Categories

Resources