Skip to content

Instantly share code, notes, and snippets.

@nazrdogan
Forked from FokkeZB/README.md
Last active August 29, 2015 14:26
Show Gist options
  • Save nazrdogan/11583f11376bed9d97db to your computer and use it in GitHub Desktop.
Save nazrdogan/11583f11376bed9d97db to your computer and use it in GitHub Desktop.
How to have a dynamic Android menu or action bar for tab groups in Titanium 3.x?
if (OS_ANDROID) {
// When the tab group first opens...
$.index.addEventListener('open', function (e) {
// Get references
var activity = $.index.getActivity(),
actionBar = activity.actionBar;
activity.onCreateOptionsMenu = function (e) {
// Clear menu
e.menu.clear();
// Pass on references with event
e.activity = activity;
e.actionBar = actionBar;
// Pass on to the active tab using a custom event
$.index.activeTab.fireEvent('onCreateOptionsMenu', e);
};
activity.onPrepareOptionsMenu = function (e) {
// Pass on to the active tab using a custom event
$.index.activeTab.fireEvent('onPrepareOptionsMenu', e);
};
// Invalidate actionbar menu, required with tab groups
activity.invalidateOptionsMenu();
});
// When the selected tab changes...
$.index.addEventListener('focus', function (e) {
// Force menu to be rebuild
$.index.getActivity().invalidateOptionsMenu();
});
}
// Open the tab group
$.index.open();
<Alloy>
<TabGroup>
<Require src="tab" nr="1" />
<Require src="tab" nr="2" />
</TabGroup>
</Alloy>
var args = arguments[0] || {},
nr = args.nr;
if (OS_ANDROID) {
var saidHello = false;
// Creating the menu
$.tab.addEventListener('onCreateOptionsMenu', function(e) {
if (e.actionBar) {
// Example: Update the action bar's title using the window's
e.actionBar.title = $.win.title;
}
// Add a menu option
e.menu.add({
title: "Menu " + nr,
showAsAction: Ti.Android.SHOW_AS_ACTION_ALWAYS,
itemId: 100 + nr,
visible: !saidHello
}).addEventListener("click", function() {
alert('Alert ' + nr);
saidHello = true;
// Invalidate actionbar menu to hide this menu item
e.activity.invalidateOptionsMenu();
});
});
// Prepare a non-actionbar menu before it shows
$.tab.addEventListener('onPrepareOptionsMenu', function(e) {
// Hide menu item once we've said hello
e.menu.findItem(100 + nr).setVisible(!saidHello);
});
}
// Settings titles & label
$.tab.title = "Tab " + nr;
$.win.title = "Window " + nr;
$.label.text = "Label " + nr;
<Alloy>
<Tab id="tab">
<Window id="win">
<Label id="label" />
</Window>
</Tab>
</Alloy>
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
<!-- OTHER STUFF -->
<android xmlns:android="http://schemas.android.com/apk/res/android">
<tool-api-level>11</tool-api-level>
<manifest>
<!-- Target Android 3.x for action bar -->
<uses-sdk android:targetSdkVersion="11"/>
</manifest>
</android>
</ti:app>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment