i have action bar in my application that displays menu items defined in my res/menu/activity_main.xml
My menu items are aligned to right on action bar. I want them to be aligned to left.
Only solutions i found for this used custom action bar, like this one: Positioning menu items to the left of the ActionBar in Honeycomb
However, i dont want to create custom layout for my menu. I want to use default menu items generated from my res/menu/activity_main.xml
.
Is this possible?
Well, i was curious about this, so i dug deep inside the SDK's source. I used
AppCompatActivity
with 3 menu item in it's XML file, and i used the defaultonCreateOptionMenu
method, which was this:After i move on from the inflate method with the debugger, i went through the following stack:
It ended in
BaseMenuPresenter
'supdateMenuView
method, this is where the revelant work is done.the method's code:
Here the
getItemView
and theaddItemView
methods do what their's name say. The first inflate a new view, and the second add it to parent. What is more important, under the debugger the parent object can be checked, it's an ActionMenuView, which inherits from theLinearLayout
and inflated form abc_action_menu_layout.xml.This means if you can get this view, you can do what you want. Theoretically, i think it can be done with lots of reflection, but it would painful. Instead of that, you can reproduce it in your code. Implementations can be found here.
According to the things above, the answer for your question is YES, it can be done, but it will be tricky.
Edit:
I created a proof of concept for doing this with reflection. I've used
com.android.support:appcompat-v7:23.1.0
.I've tried this on an emulator(Android 6.0) and on my Zuk Z1(CM Android 5.1.1), on both it works fine.
Menu XML:
Activty XML:
Activity:
Although the gravity has been changed here, on the screen this does not make any revelant difference. To get a real visible change other layout params(e.g. width ) should be tuned.
All in all, a custom layout is much easier to use.
You can do it like this: