-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Handling options menu
Since AndroidAnnotations 2.2
You can easily add options menu support in your activities, with the @OptionsMenu
and @OptionsItem
annotations.
-
@OptionsMenu
lets you specify the menu resource to use -
@OptionsItem
marks methods that receives menu selection events
Both annotations can be used independently.
Here is a simple example on how to use them:
@EActivity
@OptionsMenu(R.menu.my_menu)
public class MyActivity extends Activity {
@OptionsMenuItem
MenuItem menuSearch;
@OptionsItem(R.id.menuShare)
void myMethod() {
// You can specify the ID in the annotation, or use the naming convention
}
@OptionsItem
void homeSelected() {
// home was selected in the action bar
// The "Selected" keyword is optional
}
@OptionsItem
boolean menuSearch() {
menuSearch.setVisible(false);
// menuSearch was selected
// the return type may be void or boolean (false to allow normal menu processing to proceed, true to consume it here)
return true;
}
@OptionsItem({ R.id.menu_search, R.id.menu_delete })
void multipleMenuItems() {
// You can specify multiple menu item IDs in @OptionsItem
}
@OptionsItem
void menu_add(MenuItem item) {
// You can add a MenuItem parameter to access it
}
}
Since AndroidAnnotations 3.0
@OptionsMenuItem
can be used to inject a MenuItem in an attribute.
Be careful : Injected menu items can't be used in @AfterInject
nor @AfterViews
annotated methods, because of Android activity lifecycle. More information are available here.
Since AndroidAnnotations 4.0.0
With @InjectMenu
you can inject the Fragment's or the Activity's Menu
object.
Be careful : The menu also can't be used in @AfterInject
nor @AfterViews
as @OptionsMenuItem
.
One example for the use:
@EActivity
public class MyActivity extends Activity {
@InjectMenu
Menu menu;
}
Since AndroidAnnotations 4.0.0
@EActivity
public class MyActivity extends Activity {
@InjectMenu
void setMenu(Menu menu){
// do something with menu
}
}
Since AndroidAnnotations 2.7
You can combine multiple xml menus with @OptionsMenu
:
@EActivity
@OptionsMenu({R.menu.my_menu1, R.menu.my_menu2})
public class MyActivity extends Activity {
}
Since AndroidAnnotations 2.7
You can also use @OptionsMenu
and @OptionsItem
in Fragments:
@EFragment
@OptionsMenu(R.menu.my_fragment_menu)
public class MyFragment extends Fragment {
@OptionsItem
void menuRefreshSelected() {
}
}
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