On my Android application I am customizing the ActionBar following tips from the android developer blog and other places. I would like to be able to highlight a specific menu item on the ActionBar e.g. with a different background color because it is especially applicable to a currently visible fragment (which actually added it). However I have not found any indication that this can be done nor have I managed to do so myself yet. Is it possible? If so how?
Asked
Active
Viewed 6,987 times
6
-
Are you sure it wouldn't be easier to use a slightly different icon? Or other foreground changes that you might accomplish via your own custom inflated action view or `ActionProvider`? – CommonsWare Dec 22 '11 at 00:56
-
currently these are text and an icon would be harder to understand. In terms of the custom action view or ActionProvider... I will have to look into that. – Manfred Moser Dec 22 '11 at 01:06
-
You could change the foreground color of the text, at least if you go the action view/`ActionProvider` route. Unfortunately, Android doesn't support the ` – CommonsWare Dec 22 '11 at 01:10
-
ActionProvider is not part of the compatibility package and wrapping it seem to be more hazzle than its worth. – Manfred Moser Dec 22 '11 at 22:06
1 Answers
13
So I got this to work now with a bit of a trick to it. Here goes the fragment code
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menuItemCreateCart = menu.findItem(R.id.menuItemCreateCart);
if (menuItemCreateCart == null) {
menuItemCreateCart = menu.add(0, R.id.menuItemCreateCart, 0, R.string.Create);
}
TextView tv = new TextView(getActivity());
tv.setText(R.string.Create);
tv.setTextColor(getResources().getColor(R.color.green));
tv.setBackgroundColor(getResources().getColor(R.color.lightBlue));
tv.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
createCart();
}
}
);
menuItemCreateCart.setActionView(tv);
The main gotcha is that the onclicklistener has to be set on the view that you set as action view and not the menu item for it to work. This way you can do whatever you like.
Also note that you can NOT use getActionView to retrieve the originally set view with title because it will return null. It seem to be more of an alternative view than the actual view for default menu items..

Manfred Moser
- 29,539
- 13
- 92
- 123