I have an activity which contains an actionbar at the top and a stand alone toolbar at the bottom. I want to enable/disable an item in this toolbar depending on the value of some variable. Note, that this is inside an fragment.
If I have a normal action bar menu, I can do this in the onPrepareOptionsMenu(Menu menu) method. But this method is not called for the toolbar, nor could I distinguish which toolbar, if it would be called.
How can I prepare the toolbar and its menuitems?
This is my toolbar xml:
<?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/item_medizinische_daten"
android:title="#string/medizinische_daten"
app:showAsAction="always"></item>
</menu>
This is my code:
toolbarBottom = (Toolbar) getActivity().findViewById(R.id.toolbar_bottom);
toolbarBottom.inflateMenu(R.menu.menu_toolbar_medizinische_daten);
toolbarBottom.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.item_medizinische_daten:
Toast.makeText(getActivity(), "Medizinische Daten clicked", Toast.LENGTH_LONG).show();
break;
default:
}
return true;
}
});
The Toolbar widget has a getMenu() method which you could use to retrieve the Menu that you inflate on it. You could then use that Menu reference and through either findItem() or getItem() find its children and change them.
Related
I have a toolbar with some actionbar buttons. I would like the camera icon button NOT to appear if the
Build.VERSION.SDK_INT < 21.
in the following menu file I define the actionbar buttons:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="#+id/addons"
android:icon="#drawable/ic_add_box_black_24dp"
android:title="camera"
app:showAsAction="always"/>
<item
android:id="#+id/hellosearch"
android:icon="#drawable/ic_search_black_24dp"
android:title="camera"
app:showAsAction="always"/>
//inside the MainActivity I override the method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addons:
//we are requesting to purchase something:
Log.d("billing009","trying to start a purchase!! user has accesss(subs): "+user_has_autorenew_subs+
" didFind :: " + didFindTotalAccess);
showPurchaseDialog(styled_title);
//inHouseMethod_StartPurchase();
break;
case R.id.hellosearch:
mDrawer.openDrawer(GravityCompat.START);
return true;
HOWEVER, this method gets called when the user clicks on one of the actionbar buttons.
How can I use the toolbar object created inside onCreate: to get a hold of the Camera icon(ActionBar button), so I can set its visibility to GONE if the Build.VERSION.SDK_INT < 21 ?
//inside onCreate
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
You can do that inside onCreateOptionsMenu like
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.your_menu_xml, menu);
if(Build.VERSION.SDK_INT < 21) {
MenuItem item = menu.findItem(R.id.idOfYourMenuItem);
item.setVisible(false);
}
return true;
}
Put this method in your Activity
public boolean onPrepareOptionsMenu(Menu menu)
{
MenuItem camera = menu.findItem(R.id.addons);
if(Build.VERSION.SDK_INT < 21)
{
camera.setVisible(true);
}
else
{
camera.setVisible(false);
}
return true;
}
onPrepareOptionsMenu Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.
onCreateOptionsMenu() is called once.
onPrepareOptionsMenu() is called every time the menu opens.
From the onCreateOptionsMenu() documentation:
This is only called once, the first time the options menu is
displayed. To update the menu every time it is displayed, see
onPrepareOptionsMenu(Menu).
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 would like to add a back arrow button to the right side of action bar.
I have the following code, but it adds the back button to the the left side of the action bar.
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
What you did is enabled the action-bar's back functionality on click/touch event. If you want a button at the right of the action bar, the best/easy thing you can do is to add an overflow menu, for which you can set-up any icon you want.
There are lots of tutorials on how to do this (for ex. http://www.techotopia.com/index.php/Creating_and_Managing_Overflow_Menus_on_Android).
Essential points are as follows.
Create the layout/items for the overflow menu (filename should match with the one in the 2nd step).
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_settings"
android:orderInCategory="1"
android:showAsAction="never"
android:icon="#drawable/overflow_menu_icon"
android:title="#string/menu_settings" />
</menu>
Init the overflow inside the onCreateOptionsMenu() function, where activity_menu_app is the name of the .xml file created in the previous step.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_menu_app, menu);
return true;
}
Catch the touch events of the menu items inside onOptionsItemSelected() function.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
// do your stuff here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Please go through -Back button is not working properly in Right side of action bar
If you want to add back arrow button on the right side - Toolbar is the best option to add anything in the actionbar or Topbar.
First, you need to initialize the toolbar :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
then call the back button from actionBar :
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Finally, over right this method,
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
Solution collected from,this
Link
I wanted to display Menu in ActionBar using ActionBarActivity.
I am getting options menu while clicking options button instead of displaying in the top of action bar.
I need the options menu at top instead of clicking the options menu from 2.3 onwards
My Code :
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setSubtitle("mytest");
actionBar.setTitle("Testing");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_action, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_one:
Toast.makeText(this, "clicked search", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
My XML file :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_item_one"
android:icon="#drawable/ic_launcher"
android:showAsAction="always"
android:title="#string/action_settings"/>
<item
android:id="#+id/menu_item_two"
android:icon="#drawable/ic_launcher"
android:showAsAction="always"
android:title="#string/action_settings"/>
</menu>
Try it:
Create XML file on "../res/menu/menu_main.xml"
manu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_settings"
android:showAsAction="never"
android:icon="#android:drawable/ic_menu_settings"
android:title="#string/menu_settings"/>
</menu>
The option "never" on "showAsAction", important, if you put that the option always show on ActionBar.
Then now we must asociate this option on the MainActivity.java (class whatever you want).
MainActivity.java
public class MainActivity extends Activity {
...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Now that we define the elements of our action bar is knowing how to respond to keystrokes made by the user about them.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Log.i("ActionBar", "Settings!");;
//open Activity,Fragments or other action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
If you have morer options on your menu only add item on XML menu_main.xml and on the principal class add other "case".
For Example:
MainActivity.java
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
Log.i("ActionBar", "Save!");;
//open Activity,Fragments or other action
return true;
case R.id.menu_settings:
Log.i("ActionBar", "Settings!");;
//open Activity,Fragments or other action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_settings"
android:showAsAction="never"
android:icon="#android:drawable/ic_menu_settings"
android:title="#string/menu_settings"/>
<item
android:id="#+id/menu_save"
android:showAsAction="never"
android:icon="#android:drawable/ic_menu_save"
android:title="#string/menu_save"/>
</menu>
It is possible that this is because your device has an options button that would open the menu, so Android don't draw the launcher icon.
http://blog.vogella.com/2013/08/06/android-always-show-the-overflow-menu-even-if-the-phone-as-a-menu/
Try with return super.onCreateOptionsMenu(menu); instead of return true in your onCreateOptionsMenu method according to below android document...
http://developer.android.com/guide/topics/ui/actionbar.html#ActionItems
As per above android document...
The ActionBar APIs were first added in Android 3.0 (API level 11) but they are also available in the Support Library for compatibility with Android 2.1 (API level 7) and above.
So, If you want ActionBar in android 2.3 then you have to use Android Support Library.
Edit:
Your menu XML would need to look like this:
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto"
>
<item android:id="#+id/item_menu_ok"
android:icon="#drawable/ic_action_ok"
android:title="#string/ok"
yourapp:showAsAction="always"/>
<item android:id="#+id/item_menu_cancel"
android:icon="#drawable/ic_action_cancel"
android:title="#string/cancel"
yourapp:showAsAction="always"/>
</menu>
Replace yourapp with your app name or any namespace.
I'm not 100% sure, but it looks like your menu XML file should have a menu in it. In the menu, add the items. Like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_menu" >
<item...
<item...
</menu>
Perhaps this works.
There are also a few other things to remember in general. Android decides by itself what to show in the ActionBar (depending on what fits there and other parameters). What does not fit in the ActionBar goes into the overflow.
Do this in your oncreate()
ActionBar actionBar = getActionBar();
actionBar.show();
This should do what you want.
Action Bar
Ok, let's try another answer. If, for whatever reason, Android decides not to show the items in the action bar, then what your are seeing is indeed the correct behaviour. Items not in the action bar are shown in overflow.
One reason items don't show in the action bar is because they don't have a icon defined.
You do define an icon, as this,
android:icon="#drawable/ic_launcher"
and I suspect this is the problem. The launcher icon is of different size (larger) than the action bar items (smaller). Try defining the icon in correct size and see if it is displayed.
http://developer.android.com/design/style/iconography.html
Edit: There is an action bar icon pack to get you started so you can test to see if it works. Download it and use eclipse to import some icon..
I'm trying to add an 'Add Item' button at the top in the action bar. (To the right of the App Icon and Title).
Right under the action bar, I have two tabs that I can swipe between. I also have a menu XML file defined for the settings menu.
I thought actionbar uses a menu XML as well. So I added a actionbar menu XML, but when I use
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
actionbar.setCustomView(R.menu.actionbar);
my program crashes. I believe I'm doing this totally incorrectly.
My actionbar XML:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/item1" android:icon="#android:drawable/ic_menu_add"></item>
</menu>
I read on some tutorials that I'm supposed to add items to the actionbar and populate it via the OnCreateOptionsMenu function in mainActivity. But that's where my options menu is populated, not my actionbar.
An activity populates the ActionBar in its onCreateOptionsMenu() method.
Instead of using setcustomview(), just override onCreateOptionsMenu like this
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1:
Toast.makeText(this,"Menu Item 1 selected",Toast.LENGTH_SHORT).show();
break;
case R.id.menuitem2:
Toast.makeText(this,"Menu item 2 selected",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return true;
}