-
Notifications
You must be signed in to change notification settings - Fork 0
Fragment activity communication
Since AndroidAnnotations 3.1
The @Shared and @Share annotations eases the sharing of complex objects between a Fragment and its container Activity.
The purpose of the @Shared and @Share annotations is to let activities expose some of their members to their fragments.
The activity annotates with @Share the members that will exposed to fragments that it will contains.
The matching member of the fragment that is annotated with @Shared will then reference the activity shared member.
Fragment can have access to objects that lives within the activity lifecycle like SQLiteOpenHelper for example.
@EActivity(R.layout.activity_main)
public class MainActivity extends Activity {
@Share
String param1 = "activity string";
@Share
Bundle param2;
@Share
@Bean
MyBean bean;
@Share
int someInt = 42;
@AfterInject
void initInject() {
// You can do custom member initialization 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 = "fragment string";
@Shared
Bundle param2;
@Shared
MyBean bean;
@Shared
String isNotSharedByActivity ;
@AfterViews
void init() {
// All the members are initialized and ready !
}
}The fragment shared members must have the exact same name 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, the fragment shared members are left untouched.
If the parent activity shares variables, then the fragment shared members will be resolved. Any member that doesn't match an activity shared member will be initialized with null and a warning will be displayed in the logcat console:
The member 'isNotSharedByActivity' is not declared by the activity 'MainActivity' or is not annotated with @Share
Sharing object instances between objects with different lifecycles may create memory leaks.
To prevent that risk, all the shared variables in the fragment will be reset to null when the fragment is destroyed (on the onDestroyView() method) or recycled, whether the parent activity shares members or not.
The fragment is supposed to be deleted before the activity is.
AndroidAnnotations was created by Pierre-Yves Ricau and is sponsored by eBusinessInformations.
09/11/2014 The 3.2 release is out !
- Get started!
- Download
- Cookbook, full of recipes
- Customize annotation processing
- List of all available annotations
- Release Notes
- Examples
- Read the FAQ
- Join the Mailing list
- Create an issue
- Tag on Stack Overflow