I am working with multiple Fragments
under Android and am confused on how to send and receive data from embedded apps.
For a simple explanation, I have a ListFragment
and a MapFragment
using the method explained here. This means that the List
lives in the ListFragment
class, however the MapActivity
is an Activity
that is called under the LocalActivityManagerFragment
.
Everything works on the individual Fragments
: Lists
of waypoints, waypoints and current location implemented on the MapFragment
. I also understand how to use getFragmentManager()
to get individual Fragments
and use their events. However, I cannot use this method to access a function under MapActivity
. How can I use a command such as goToLocation
(created under MapActivity
) if I click on an item on the ListView
, if I can't simply use getFragmentManager
??
For communication between a Fragment and an activity:
Activity > Fragment:
Call on the public methods of the fragment using this.
TestFragment testFrag = (TestFragment) getFragmentManager().getFragmentById(R.id.testfragment);
if(testFrag != null && testFrag.isAdded())
testFrag.testMethod("Test");
Fragment > Activity
To send messages to the activity you need to use an interface so in the fragments class add this: (Not in any method)
public interface testInterface{
public void testMethod(String test);
}
testInterface mCallback;
@Override
public void onAttact(Activity a){
try{
mCallback = (testInterface) a;
}catch(Exception e){
//TODO
}
}
then in any method you can go and call this:
mCallback.testMethod("hello");
then for the activity make it so it implements testInterface
and import the interface
and then have this method in the activity
@Override
public void testMethod(String testString){
}
:) Just ask for anything more.
Edit
From my first read of your question I thought this is what you wanted sorry, could still cover what you wanted.
I think what your asking for is just a onItemClick method right?
so in the interface you could have
public void onItemClicked(AdapterView<?> parent, View view, int position, long id);
then when onItemClick has been called in the fragment you can use this in it
mCallback.onItemClicked(parent, view, position, id);
and then in the activity, given its implementing the interface you can have
@Override
public void onItemClicked(AdapterView<?> parent, View view, int position, long id){
}