At school we're now learning on how to make fragments more universal by using interfaces. This technique is still kinda abstract and I don't really know when/how to use it.
Can anybody point me to some resources on how to use that technique (Could it be called interface callbacks?)
All help is very appreciated!
Here are steps:
Download sample data from http://developer.android.com/training/basics/fragments/index.html(given in right side) and also look at url to how to add fragments from xml or dynamically to performing fragment transaction operations..
Then would recommend you to go through with fragment guide..http://developer.android.com/guide/components/fragments.html
Once you understand complete life cycle and its fragment callback methods then would be easy to understand example given by Google as sample.
To defining interface in fragment to calling interface or passing callback to activity..
Let’s say you have two fragments which shows list as article titles and article details.
Set your list view using list adapter in oncreateview method.
So when user click on article, system call onListItemClick callback method.
Call interface here and pass article position
Define interface and pass position in method which activity will override.
In on attach method instantiates an instance of interface by casting the Activity, If the activity has not implemented the interface, then the fragment throws a ClassCastException. On success.
Override interface method to display article details by passing position as bundle data to Fragment2.
Hope it will help you to understand sample code.
The callback approach, as you would call it, is as simple as
Listener
interface found in many parts of Java or Android. You may check the Observer pattern if you want to learn about a very general description. But if you already understand how to work with Listener, you will easily get the point about callbacks.NOTE: Do not mix it with Callback term - these are not the same.
Suppose we have
Activity
MyActivity andFragment
MyFragment. We want to post some data from Fragment to Activity. Then let us create an interface within MyFragment:Our MyActivity will look like this:
So, MyFragment knows nothing about the implementation of it's callback. But it knows, that it can call the method
onPostData(Object o)
on the instance of PostDataCallback, which is held in the variablemCallback
.Thus, when MyFragment triggers it's
mCallback.onPostData(data)
, MyActivity get's the result.Exactly the same approach would work if we wanted to send message from MyActivity to MyFragment, but we would do it do it vice versa: the trigger method, callback interface definition and instance would reside in MyActivity, and MyFragment would implement the interface.
You can simple create new Android Application project in eclipse. Then create Android Object (Fragment) with callback methods. This will give you an idea for interfaces.
And then the same you can apply for activity to fragment.