Skip to content
This repository has been archived by the owner on Feb 26, 2023. It is now read-only.

Fragment activity communication

PerfectCarl edited this page Jan 12, 2014 · 10 revisions

Since AndroidAnnotations 3.1

Introduction

Sharing objects between a Fragment and its container activity is not straightforward. Fragments and activities are independent and don't know each other:

The purpose of the @Shared and @Share annotations is to let activities expose some of their private variables to their fragments. Fragment can have access to objects that lives within the activity lifecycle like SqliteHelper for example.

The parent activity declare the variable that should be exposed.

Sample

@EActivity(R.layout.activity_main)
public class MainActivity extends Activity {

	@Share
	String param1 = "this is a success";

	@Share
	Bundle param2;

	@Share
	@Bean
	MyBean bean;

	@AfterInject
	void initInject() {
                // You can do custom member initialisation here
		param2 = new Bundle();
		param2.putString("are we", "done?");
	}
}

And the fragment declares

@EFragment(R.layout.fragment_main)
public class MainFragment extends Fragment {

	@Shared
	String param1 = "this is a failure";

	@Shared
	Bundle param2;

	@Shared
	MyBean bean;

	@AfterViews
	void init() {
		// All the members are initialized and ready !
	}
}

The shared variables in the fragment must have the same as the ones that the activity shares.

All the variables will be initialized and available after the @AfterViews event.

**Note: ** due to activity/fragment lifecycle the shared variables are not initiliazed by the the time the fragment'@AfterInject is called.

If the parent activity doesn't share any variables that matches the names of the fragment's variables, a warning is displayed in the logcat console.

Memory management and leaks

Sharing object instances between objects with different lifecycles may create memory leaks. To prevent that risk, all the shared variables in the fragment are set null when the fragment is destroyed (on the onDestroyView() method)

The fragment is supposed to be deleted before the activity is.

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Extending AndroidAnnotations

Clone this wiki locally