Reuse fragment structure and passing complex arguments - android

I have implemented a DialogFragment class which shows a dialog and call a custom listener when its button is pressed.
Since I want to reuse this class in many projects I need to pass the listener when I create the fragment. However I don't know how I could do it.
I know I should not pass the listener in the constructor because Android could call the default constructor if it has to recreate the fragment and I cannot pass the listener via Bundle arguments because Bundle does not support it.
The unique solution I found is make the activity implement the custom listener and check it in onAttach method. The problem is that this way would limit the implementing classes to the owner activity and maybe it does not fit to the application.
Does you find a better solution?
Thanks!

You normally have a static newInstance() method to create your fragment and pass in any values your fragment might need. That's the method to pass your listener to.
Have a look here where a newInstance() method is also used as an example:
http://developer.android.com/reference/android/app/Fragment.html

Related

What is difference in 2 ways transfer data to fragment from activity using getArgument() and getActivity.getXXX()

I wonder the difference between two ways of transfering data from activity to fragment.
One is using getArgument() and setArgument(). I can transfer data using these methods at Fragment's contruction time.
Another is using getActivity() method. Like this way
((HostActivity)getActivity()).getXXX()
After declaring getter method of data Fragment may use, call this method in fragment through getActivity() and Type casting.
I think second one is easier and convenient. Because get/setArgument() can be called only Fragment's contruction time.
So, How to apply these 2 way to sending and getting data between Activity and Fragment?
A Fragment represents a behavior or a portion of user interface in an
Activity. You can combine multiple fragments in a single activity to
build a multi-pane UI and reuse a fragment in multiple activities.
Because fragment can reuse in multiple activity, if you use getActivity() with type casting, you must check instanceOf activity before call method. And each of activity use that fragment, you must implement method getXXX().
Use newInstance method in fragment, you only pass require parameter for it.
If you create fragment for individual activity, you can apply 2 ways transfer data.
The fragment has an independent lifecycle from activity with specific threads, functions and handlers. So you can use getters/setters Activity variables like a global variables and bundle data (arguments) to independent fragment variables.

Populating fragment fields from activity

I have a ViewPager of 3 fragments. All 3 fragments are of the same type, with identical layouts, but they are to hold different (text) information. I am trying to create my activity, where I create the fragments and prepare the text data that I will populate my fragments with. However, I can't seem to work with the fragments from within my activity. All the activity's lifecycle methods are executed before the fragment lifecycle methods. So if I try to update a textview in a fragment from within my activity, it won't work, because the textview is null in the fragment.
I'm going to need to make periodic updates to the fragments, so passing the data as a bundle is not an option. Plus, since I'm passing lots of text, I'm using a StringBuilder object, which is not something I can pass in a bundle (unless I make it Parcelable, which I don't want)
I think I could run a method from within my fragment class that would execute during fragment creation, but that means all 3 fragments would run this method. That's not really the level of control I'm looking for.
Is there a neat way to make this work?
Thanks
Keep references to your fragments, and let them all implement an interface with a common update-method. As an example, let's make it super clear and call the interface Updatable with one method called 'update':
public interface Updatable {
public void update(String text);
}
Now, in your Activity's onCreate, save references to your Updatables there (i.e. when you lookup or instantiate your Fragments).
It should now be trivial to update your Fragments when necessary from the Activity. Needless to say, the fragment implementation of the update code needs to do the actual update of the TextView(s).
If the update implementation is exactly the same for all your Fragments, your could save some lines of code and make a base class which implements Updatable and extends Fragment.
you might able to populating fragment fields during onActivityCreated(Bundle savedInstanceState).
Refer to this site for more information about fragments' life cycle:
http://developer.android.com/guide/components/fragments.html
You should consider using Observer pattern... there is a really great implementation which you can include as gradle dependency called EventBus:
https://github.com/greenrobot/EventBus
You can use Otto Bus to send data to your fragments from your activity.
http://square.github.io/otto/
Create a new bus in you application class
Bus bus = new Bus();
Create an event that contains your data which you'll pass to fragments.
bus.post(new MyDataEvent(data));
Register your fragment in your fragment's onResume() (Do not forget to unregister in your fragment's onPause())
bus.register(this);
And get data with subscribe in your fragment
#Subscribe
public void onDataReceived(MyDataEvent event) {
// TODO Do what ever you want
}
I hope this'll help you.

What's the difference between 'this' and 'getActivity()'?

I have an idea they both get the 'context' so that functions know how they fit into the scheme of things, is this right?
Any clues for the evolving ape?
this is a reference to the current class you are. It can be an Activity, Fragment, Adapter, View, etc. And when you use it what you are doing is just passing a reference of the current object of that class.
Let's say you are working on a custom View. Anywhere in the code of that view where you call this will be interpreted as the View itself, so the value of this changes depending on what class you are.
The method getActivity() is defined only in the Fragment class and any other class extending Fragment and this method returns and Object of the type Activity.
On Android development is very common mixing those two because most of the applications code is in Activity classes, and calling this on an Activity class will return an Activity object but as you can see they are not the same thing.
You can read more here

Android : Accessing container activity object from fragment using putExtra?

I am building a tab interface using Action bar and fragment. I would need assistance in sending data from container activity to the fragment.
To elaborate, I have job object in container activty. And I have created few tabs based on the information in job object (like company details, experience details etc). I need to pass the job object to these fragments so that it can display respective information.
I have created container activity and tab fragments. I would need an example on how to pass the object across them. I cannot use intent.putExtra. Can I access parent container's object from fragment?
Any help shall be appreciated.
Thanks.
Make the method in your activity, e.g getJob that will return the Job object and its information
MyActivity extends Activity{
Job mJob;
public Job getJob(){
return this.mJob;
}
}
then in your Fragment you do this:
MyFragment extends Fragment{
#Override
public void onActivityCreated(){
super.onActivityCreated();
((MyActivity)this.getActivity()).getJob();
}
}
use getActivity and the method getJob(); to get the object
There are multiple ways of achieving this.
Make a static variable to hold your data and access that data from inside the fragments - this is the most fast but it creates bad design patterns if used improperly.
A way of Fragment-to-Fragment communication possible through the parent Activity is posted here: http://developer.android.com/training/basics/fragments/communicating.html You can use the sample code to just do a Activity - Fragment data send.
The top voted answer here: Accessing instance of the parent activity? mentions a way to avoid using static data (1.) and contains source code examples using ActivityGroup
"If you need access to some values in your First activity without
making a static reference to it, you could consider putting your
activities in an ActivityGroup."
What you choose is your preference, these are just a few options!
Edit: I'm not sure if number 3 will work with fragments since I haven't tested a method similar to it, the example is Activity - Activity communication.

How to create a Fragment instance correctly in Android

I have seen different ways to create a Fragment. Can somebody clear me up whats the difference between the methods and what is the best way and when to use which.
new MyFragment() I myself use this, because it seemed natural to me.
MyFragment.instantiate(Context context, String fname, Bundle args) This looks like a custom static method to create a Fragment but i've never seen it used.
My.Fragment.newInstance() This one is in an Android Developer Example.
What's each options purpose?
The most difference is when to use each sample:
1- Creates a new fragment object each time called.
2- Same as calling the empty constructor, but, if you set the fragment to setRetainInstance(true), this will not work if you use the empty constructor.
3- My.Fragment.newInstance(), method to get the single instance from a static fragment, If you have a static class extending fragment, you can create a Method to return a new fragment or the current fragment, its the singleton pattern.
4- Inflate from xml, same as calling the empty contructor, the Android FrameWork take care of attachement to the view, but the instance will be kept with the hole activity lifecycle, needs more memory and cannot be reused multiple time.

Categories

Resources