Reputation: 85
I'm trying to create my own style of a menu item but haven't managed to do it yet.
There are some ways I do it: 1)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.drawable.menu, menu);
return result;
}
menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/add"
android:icon="@android:drawable/ic_menu_add"
android:title="@string/add" />
</menu>
2)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
MenuItem m1 = menu.add(0, 0, 0, R.string.add);
m1.setIcon(android.R.drawable.ic_input_add);
return result;
}
But in both cases my menu item stays "standard". What should I do to change it's size, location, etc. ?
Upvotes: 3
Views: 908
Reputation: 6380
Firstly, I wouldn't recommend defining your own style of menu. In my personal opinion this isn't something that should be changed. It will also be useless for ICS+ devices as they will not have a dedicated menu button.
However, if you wish to do it, you are going to have to step away from the existing menu set up as it is not possible to change the default behavior.
What you are going to need to do is create a hidden layout inside the existing layout for your activity, then hook onto the getKeyDown event to hide/show this layout.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
myCustomMenu.toggleVisibility();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
The method could look something like this
public void toggleVisibility() {
LinearLayout myCustomMenuLayout = (LinearLayout) findViewById(R.id.myCustomMenu);
if (myCustomMenuLayout.getVisibility() == View.GONE) {
myCustomMenuLayout.setVisibility(View.VISIBLE);
} else {
myCustomMenuLayout.setVisibility(View.GONE);
}
}
When it comes to the layout, it is probably for the best if you create it in a separate layout then just reference it like I have below. This is so you can reference it multiple times without the code duplication.
<include android:id="@+id/myCustomMenu" layout="@layout/customMenu" visibility="gone">
From there you just need to populate the menu and define the onclicklisteners etc
Upvotes: 1