Fragment activity communication
Since AndroidAnnotations 3.1
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.
@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.
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.
19/11/2020 The 4.8.0 release is out !
- Get started!
- 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
- Ask on Gitter