I would recommend you read this documentation.
call to function Ask() of MainActivity from fragment2.
For this you need a create a interface
in your fragment2
. The below code is an example from the document. You shouldn't ignore the onAttach
method in your fragment as well.
public class Fragment2 extends ListFragment {
OnCallActivityListener mCallback;
// Container Activity must implement this interface
public interface OnCallActivityListener {
public void callAskMethod();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnCallActivityListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
}
Now the fragment can deliver messages to the activity by calling the callAskMethod()
method (or other methods in the interface) using the mCallback instance of the OnCallActivityListener
interface.
For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.callAskMethod();
}
After that you should implement the interface in your host activity.
public static class MainActivity extends Activity
implements Fragment2.OnCallActivityListener{
...
public void callAskMethod() {
// Do something here
ask();
}
}
So that is it. You have called ask()
method from fragment2
fragment.
I want to import results into a page called from fragment2.
The host activity can deliver messages to a fragment by capturing the Fragment
instance with findFragmentById()
, then directly call the fragment's public methods.
In your `MainActivity you can call send the result to the fragment.
Fragment2 fragment2 = (Fragment2) getSupportFragmentManager().findFragmentById(R.id.article_fragment);
So you have a instance value of the Fragment2
in MainActivity
. So you can any public method of the fragment2
from there.
for example
fragment2.doSomething();
That's it.