I have a Toolbar within my app which I would like to modify it contents dynamically, during the app execution (in other words, on run-time).
For example, the app is capable of taking and previewing photos; once that photos are previewed, the user is able to select some photos and perform a sending action to a server. I want also to make the user able to delete photos once that some of them are selected and for doing that I would like that the "delete" item on the action bar (identifiable via the trash icon) will be visible only when one or more photos are selected.
Is this possible to do?
If yes, how?
In other words and, more generically, I want to control items (visibility) in the toolbar, setting the code as they will be "visible" only when some conditions are "true" (in the example above, when photos are selected or, in a different example, when user is logged) and invisible when they are "false" (when user isn't logged).
For now I just need to "remove" (or make invisible) items in the Toolbar, but it will be useful also to know if is possible to add items in the toolbar on run-time.
I'm adding some code which can help to understand the problem.
app_bar.xml file in "/res/layout", which graphically defines the Toolbar
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:elevation="4dp"
android:theme="#style/ToolbarTheme" />
menu_resources.xml file, which defines the Toolbar items
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- "User favourite function", should appear as action button if possible -->
<item
android:id="#+id/action_app_icon"
android:icon="#mipmap/ic_launcher"
android:title="#string/action_bar_app_icon"
app:showAsAction="always" />
<!-- Settings, should always be in the overflow -->
<item
android:id="#+id/action_delete"
android:icon="#drawable/trash"
android:title="#string/action_bar_delete"
app:showAsAction="always"/>
<!-- Settings, should always be in the overflow -->
<item
android:id="#+id/action_settings"
android:icon="#drawable/settings"
android:title="#string/action_bar_settings"
app:showAsAction="never"/>
<!-- About, should always be in the overflow -->
<item
android:id="#+id/about"
android:icon="#android:drawable/ic_dialog_info"
app:showAsAction="never"
android:title="#string/action_bar_about"/>
Part of the activity in which the toolbar is
public class myClass extends AppCompatActivity implements View.OnClickListener {
// Instantiating a toolbar
private Toolbar toolbar;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_class);
// Adding toolbar to the activity
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
}
// The method that creates an options menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_resource, menu);
// This make the delete item invisible
menu.findItem(R.id.action_delete).setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// Perform the settings action
return true;
case R.id.about:
// Perform the about
return true;
case R.id.action_delete:
deletePhotos();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public static void manageSelection(Boolean state, int position){
if (photoArray.getNumberSelected() == 0) {
// disable the trash icon and its functionality;
} else {
// enable the trash icon with its functionality;
}
}
// This method allows to deleteItems images to the array
public void deletePhotos() {
//code for deleting photos
}
}
Thanks for your time.
Try this code in your activity please:
public class ActivityClass extends AppCompatActivity {
MenuItem menuItem; // Make global toolbar's menuItem
.
.
.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
menuItem = menu.findItem(R.id.toolbar_action_button) // Your toolbar´s button ID and save it in your global menuItem
return super.onCreateOptionsMenu(menu);
}
public void showMenuItem(){
menuItem.setVisible(true); // Call this method in runtime when you need show it
}
public void hideMenuItem(){
menuItem.setVisible(false); // Call this method in runtime when you need hide it
}
[EDIT]
Thanks to Alessandro Iudicone´s comment we have an alternative way to get the toolbar´s menu too without the global MenuItem but only global Toolbar instance:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
return super.onCreateOptionsMenu(menu);
}
public void showMenuItem(){
toolbar.getMenu().findItem(R.id.toolbar_action_button).setVisible(true);
}
public void hideMenuItem(){
toolbar.getMenu().findItem(R.id.toolbar_action_button).setVisible(false);
}
Hope it helps :)
For hiding the icon:
toolbar.findViewById(R.id.menu_item_id).setVisibility(View.INVISIBLE);
For adding a view to the toolbar:
TextView textView = new TextView(MainActivity.this);
textView.setText("Hello World");
toolbar.addView(textView);
This only works for views on the toolbar itself, not for the overflow menu. You'll probably have to use code found in this stack overflow answer if you want to mess with the overflow menu: Android Toolbar overflow menu view id
I am having an issue where i have 2 items in my action bar (one 'refresh' button and one 'Save' Button, but for some reason they do not show, instead they are nested inside an options menu (3 dots). Would anyone know how to remove the 3 dots menu and display my 2 items? I have tried many things but ultimately I just end up removing all three items. Thanks in advance.
Here is my code
add_event_action.xml (this is my menu xml)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_refresh"
android:showAsAction="always"
android:icon="#drawable/ic_action_refresh"
android:title="Refresh"/>
<item
android:id="#+id/action_save"
android:showAsAction="always"
android:title="#string/save"/>
</menu>
Here is my Java class
public class RandomActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_list);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_event_action, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.action_refresh:
Toast.makeText(this, "Refresh selected", Toast.LENGTH_SHORT)
.show();
break;
// action with ID action_settings was selected
case R.id.action_save:
Toast.makeText(this, "Save selected", Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
return true;
}
}
If I understood correctly, you need two menu buttons in your toolbar.
This works for me, place it in your menu.xml:
<item
android:id="#+id/done"
android:title="#string/done"
app:showAsAction="always|withText"/>
Try to use app:showAsAction instead of android:showAsAction
To expand on the other answers somewhat:
When your activity extends from AppCompatActivity, your menu items should use app:showAsAction. When your activity does not (that is, when you're not using the AppCompat support libraries), your menu items should use android:showAsAction.
Documentation: http://tools.android.com/tips/lint-checks
AppCompatResource
Summary: Menu namespace
Priority: 5 / 10
Severity: Error
Category: Correctness
When using the appcompat library, menu resources should refer to the
showAsAction in the app: namespace, not the android: namespace.
Similarly, when not using the appcompat library, you should be using the android:showAsAction attribute.
I have an action bar with a drawer on the left. I want to add another menu on the right side of the action bar. It can be three dots or a button or anything else. Is there any way to do this?
Thanks :)
For achieving 3 dots menu in your actionBar, in your activity (which extends AppCompatActivity or ActionBarActivity), you override the creation of options menu like below
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.your_menu, menu);
return true;
}
Where this R.menu.your_menuis a resource item present in your res/menu folder. One sample menu resource file content
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="your_package.your_activity">
<item
android:id="#+id/action_edit"
android:orderInCategory="100"
android:title="#string/action_edit"
app:showAsAction="collapseActionView"/>
<item
android:id="#+id/action_settings"
android:orderInCategory="101"
android:title="#string/action_settings"
app:showAsAction="collapseActionView"/>
</menu>
This will show a menu with both the options collapsed by default. To listen for clicks on these menu items, you override onOptionsItemSelected and perform the necessary action
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
//Do something
...
return true;
case R.id.action_edit:
//Do something else
...
return true;
}
return super.onOptionsItemSelected(item);
}
You can create a layout for your ActionBar and then use something like the following in your activity:
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_action_bar);
And in your R.layout.custom_action_bar create the buttons you need.
I am very new to Android and Java programming. What I am trying to do is to get Actionbar with couple of tabs (11 in final). I have managed to install ActionBar Sherlock but then I am stuck with adding tabs to actionbar. From what I read it looks that also I would need to add separate Fragment for each tab. Is there a simple solution how to make that work.
You don't need to have a fragment per tab in the action bar. It should just be as simple as defining your menu in xml, then in your activity initialising the action bar with your menu.
For instance your menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/my_menu_item"
android:showAsAction="always|withText"
android:title="Tab name here"/>
</menu>
Then in your activity override onCreateOptionsMenu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}
Then you'll need to override onOptionItemSelected to respond to when a tab is pressed:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.my_menu_item:
//do something
}
return super.onOptionsItemSelected(item);
}
How to disable/hide three-dot indicator(Option menu indicator) on ICS handsets which does't have menu button. ?
I am running application as <uses-sdk android:minSdkVersion="5"/> in Manifest, code is compiled with 4.0. Three-dot indicator shows on every screen.
Example for preference activities i don't want show Three-dot indicator, since it does't have any menu options.
Adding android:targetSdkVersion="14" in manifest it works. However don't want hide/remove three dots button on all screens . Only in preference activities don't want to show this three dots button.
Override onPrepareOptionsMenu() in the fragment of the preference with this:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.menu_settings);
item.setVisible(false);
super.onPrepareOptionsMenu(menu);
return true;
}
if you have more then one item set all the items visibility flag to false
and add the command setHasOptionsMenu(true);
to the onCreate command
after you will set all the visibility of the items to false the menu will disappear
on activity, the only difference is the onPrepareOptionsMenu is boolean and you don't need to add the setHasOptionsMenu(true); command on the creation
I just deleted the method :
#Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
then that three-dot-menu goes away (:
Hope it helps.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
There is no way to show/hide "three-dot" menu indicator for a single activity. You can hide this menu indicator only for entire app by specifying android:targetSdkVersion="14" (or above) in your manifest file.
However, this menu indicator is not showing on preferences activity if it extends from native android.preference.PreferenceActivity class. I have this scenario implemented in a few of my apps, and it works perfectly.
I assume you are using some custom preferences implementations which does not extends from PreferenceActivity. Android Dev Team suggests to always use PreferenceActivity for any preferences in your applications.
Way too late to the party here, I was trying to remove all my menu items and the 3-dots(option menu indicator), I did differently than the solution given here I am surprised that nobody had told it. There is a visibility tag that can be set to false and no changing of code in activity is required visibility=false does the trick
in res / menu /..
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
visibility=false
android:title="#string/action_settings"/>
override method and return false remember of not call super
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
Remove this item in res / menu / main.xml
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/action_settings"/>
In addition: do not add an item that has showAsAction="never"- this will avoid the dots from showing. If you have more items than can not be shown at once the dots will be there again (and they are items that are flagged ifRoom).
Following code worked for my app. Tried on Samsung Galaxy S4 (Android 4.3) and Nexus 4 (Android 4.2):
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.action_settings);
item.setVisible(false);
return true;
}
for hiding 3 dots in actionbar/ toolbar
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_dash_board_drawer, menu);
return false; //for visible 3 dots change to true, hiding false
}
You can actually change the Android targetVersion thus forcing the 3-dot menu to either hide or show. You need to override onCreate of your Activity like this :
#Override
public void onCreate(Bundle savedInstanceState) {
getApplicationInfo().targetSdkVersion = 10; // To enable the 3-dot menu call this code before super.OnCreate
super.onCreate(savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
getApplicationInfo().targetSdkVersion = 14; // To disable the 3-dot menu call this code before super.OnCreate
super.onCreate(savedInstanceState);
}
Tested on Android 4.x.x and Android 3.0
I just excluded the "onCreateOptionsMenu"-method:
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_planos, menu);
return true;
}
If you simply want to hide the button, this solution is a bit of a hack but works across all versions of Android (using AppCompat) and doesn't affect your other menu items:
styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light">
...
<item name="android:actionOverflowButtonStyle">#style/AppTheme.Overflow</item>
<!-- If you're using AppCompat, instead use -->
<item name="actionOverflowButtonStyle">#style/AppTheme.Overflow</item>
</style>
<style name="AppTheme" />
<style name="AppTheme.Overflow">
<item name="android:src">#null</item>
</style>
If you want the Overflow button hidden only on some screens, you could make this an alternate theme (change AppTheme above to AppTheme.NoOverflow) that only certain activities use :
AndroidManifest.xml
<activity android:name=".NoOverflowActivity"
android:theme="#style/AppTheme.NoOverflow" >
This effectively just makes the icon have no width and height. I rarely recommend opposing design guidelines but in my scenario we used dedicated hardware that did not properly report a menu button was present.
Just want to improve #war_hero answer.
If You wanna set the visibility on run time You can use oncreateoptions menu parameter like this
Menu overflow;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mymenu, menu);
this.overflow = menu;
return super.onCreateOptionsMenu(menu);
}
and then make a function to show or hide any menu item according to the index. for e.g.
public void hideorShowMenuItems(boolean bool){
overflow.getItem(1).setVisible(bool);
overflow.getItem(2).setVisible(bool);
overflow.getItem(3).setVisible(bool);
overflow.getItem(4).setVisible(bool);
overflow.getItem(5).setVisible(bool);
}
Copy paste this code in main.xml in menu folder
you just need to make the item android:visible="false"
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:visible="false"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
Should be:
<item
android:id="#+id/linearlayout_splash"
android:orderInCategory="100"
android:showAsAction="never"
android:visible="false"
android:title="#string/action_settings"/>
If MainActivity is
public class MainActivity extends AppCompatActivity
In MainActivity Class, Remove the below code.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Do it like this.
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(leftDrawer);
return (!drawerOpen);
}
I am checking if my navigation drawer is visible I will hide the menu and vice versa. You can use it according to you requirement. Hope this helps. Happy Coding. :)
This is how I find a solution of mine. It maybe helpful.
#Override
public boolean onKeyDown(int keycode, KeyEvent event ) {
//KEYCODE_MENU
if(keycode == KeyEvent.KEYCODE_MENU){
/* AlertDialog.Builder dialogBuilder
= new AlertDialog.Builder(this)
.setMessage("Test")
.setTitle("Menu dialog");
dialogBuilder.create().show();*/
return true;
// finish();
}
return super.onKeyDown(keycode,event);
}
I just used
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Where R.menu.main is only an empty menu xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" ></menu>