Cody Blog

Data Sharing between Fragments and Activity

Source: Data Sharing between Fragments and Activity in Android - Stack Overflow

Activity -> Fragment [prefered]

In your activity : create a bundle and use:

fragment.setArguments(bundle)

In your fragment : use Bundle bundle:

getArguments()

Activity -> Fragment

In your fragment : create a public method

public void methodForActivity(...) {
    ...
}

In your activity : call an active fragment public method :

getSupportFragmentManager().findFragmentById(R.id.your_fragment).publicMethod(args)

Fragment -> Activity [prefered]

In your fragment, create an interface with getter and setter methods to hold the interface reference which will be implemented by the activity.

In your activity, implement the interface, and using the setter method to pass self refernece to fragments.

Fragment -> Activity

In your activity : Create public getter and setter or other methods

In your fragment : called public activity getter, setter or other methods using :

getActivity().getSomething()

android

Related Posts

Comments