Sends a message to the previous fragment
I have two fragments. For example, fragment A and fragment B. Now after clicking a button in fragment A, I start using the code below fragment B
getFragmentManager()
.beginTransaction()
.replace(R.id.framelayout, companyDetailsFragment)
.addToBackStack(null)
.commit();
Now there is another back button in fragment B. After clicking the button
I’m using the following code to remove that particular fragment
getFragmentManager().popBackStack()
Now what I want is that when the user hits the back button, I want to pass some specific data to the previous fragment A. The question is
The onStart()
method wasn’t called, so I didn’t get any value.
So how do you get the data? Any help would be appreciated.
Solution
I can solve it, here is my answer
1. Create an interface
public interface OnButtonPressListener {
public void onButtonPressed(String msg);
}
2. Implemented in Fragment B
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
buttonListener = (OnButtonPressListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement onButtonPressed");
}
}
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().popBackStack();
buttonListener.onButtonPressed("Message From First Fragment");
}
});
3. Use that listener in the Activity class
public class ParentActivity extends FragmentActivity implements OnButtonPressListener {
@Override
public void onButtonPressed(String msg) {
FragmentA Obj=(FragmentA) getSupportFragmentManager().findFragmentById(R.id.framelayout);
Obj.setMessage(msg);
}
}
4. Create a method in the Fragment A class
public void setMessage(String msg){
System.out.print("got it");
}
From this Get quoted. Hope this will help others. If anyone has other good solution please answer this question.