Search code examples
androidinterfaceandroid-activitycallbackfragment

How to make a callback between Activity and Fragment?


I have this interface in my activity.

public interface LogoutUser {
    void logout();
}

My fragment implements this interface, so in my fragment, I have this:

@Override
public void logout() {
    // logout
}

In my activity I call

mLogoutUser.logout();

Where mLogoutUser is of the type LogoutUser interface.

My issue is the mLogoutUser object that is null. How can initialize it?

Thank you!


Solution

  • Android Fragments - Communicating with Activity

    You need to get a reference to your fragment with getFragmentById() or getFragmentByTag()

    getFragmentManager().findFragmentById(R.id.example_fragment);