Sending events back to an activity with callback interface

suggest change

If you need to send events from fragment to activity, one of the possible solutions is to define callback interface and require that the host activity implement it.


Send callback to an activity, when fragment’s button clicked

First of all, define callback interface:

public interface SampleCallback {
    void onButtonClicked();

Next step is to assign this callback in fragment:

public final class SampleFragment extends Fragment {

    private SampleCallback callback;

    public void onAttach(Context context) {
        if (context instanceof SampleCallback) {
            callback = (SampleCallback) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement SampleCallback");

    public void onDetach() {
        callback = null;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.sample, container, false);
        // Add button's click listener
        view.findViewById( View.OnClickListener() {
            public void onClick(View v) {
                callback.onButtonClicked(); // Invoke callback here
        return view;

And finally, implement callback in activity:

public final class SampleActivity extends Activity implements SampleCallback {

    // ... Skipped code with settings content view and presenting the fragment

    public void onButtonClicked() {
        // Invoked when fragment's button has been clicked

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents