I am having 2 Fragments
A and B. I am starting Fragment B
from Fragment A
. I need to pass data from Fragment B
to Fragment A
before Fragment B
is closed. Its like startActivityForResult()
idea.
Here in Fragment A I am calling Fragment B:
FragmentB calendarDialog = new FragmentB();
calendarDialog.setTargetFragment(CurrentPanchangDialog.this, 1);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
transaction.add(android.R.id.content, calendarDialog).addToBackStack(null).commit();
Now in Fragment B I am calling something like this while closing:
getTargetFragment().onActivityResult(
getTargetRequestCode(),
Activity.RESULT_OK,
new Intent().putExtra("data", "datafrom C")
);
getActivity().getSupportFragmentManager().popBackStackImmediate();
Now in the Base Activity I am overriding onActivityForResult()
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment pFragment = getSupportFragmentManager().findFragmentById(R.id.content);
if (pFragment instanceof CurrentPanchangDialog) {
if (pFragment != null) {
pFragment.onActivityResult(requestCode, resultCode, data);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
I am not getting the data back to Fragment A from Fragment B.
Delegate Pattern
• Create an interface with one method like this one:
public interface FragmentCallback {
void onDataSent(String yourData);
}
• Implement this interface in your FragmentA and implement onDataSent() method:
public class FragmentA implements FragmentCallback {
@Override
void onDataSent(String yourData){
//Do something with your data
}
}
• Declare this interface variable in Fragment B and create a public setter method:
public class FragmentB {
private FragmentCallback fragmentCallback;
public void setFragmentCallback(FragmentCallback callback) {
this.fragmentCallback = callback;
}
}
• Somewhere withing FragmentA set it as a callback on FragmentB instance:
fragmentB.setFragmentCallback(this);
• Path data from FragmentB to FragmentA (you can do it from one of fragment's lifecycle method if data should be sent when FragmentB is about to be closed):
public class FragmentB {
public void onDestroy() {
if(fragmentCallback != null){
fragmentCallback.onDataSent("Some data from FragmentB");
}
super.onDestroy();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With