I have a callback interface.
public interface RowCallback {
void callOnRowAction(String action);
}
My fragment FragmentA
is attached to ActivityA
in which FragmentA
is defined as follows:
class FragmentA extends Fragment implements RowCallback {
@Override
void callOnRowAction(String action) {
. . . Custom implementation . . .
}
... Other methods . . .
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mButton = view.findViewById(R.id.my_button);
mButton.setOnClickListener((view) -> {
// I want to pass the callback instance (which is FragmentA) to activity B.
Intent intent = new Intent(getActivity(), ActivityB.class);
. . . Some more intent initialisation. . .
startActivity(intent);
});
return view;
}
}
ActivityB source Code
public class ActivityB extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = createFragment(getIntent());
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
private Fragment createFragment(Intent intent) {
FragmentB fragment = new FragmentB();
Bundle bundle = new Bundle();
. . . . initialise bundle . . .
// I want to pass the callback instance from the intent to the callback function.
// In this example, the callback instance would be an instance of fragment A.
fragment.setArguments(bundle);
return fragment;
}
}
In an instance of FragmentB, I want to invoke a call back method should a logical condition be satisfied.I want to return to ActivityA/FragmentA after the callback function has been invoked by calling getActivity().finish();
How can I achieve something like this?