How to display icons in actionbar and how to handle click events - android

Trying to add actionar icons to actionbar and i'm using support library here is link i'm following developerspage
and here is my code to implement it
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == R.id.toggle) {
if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
mDrawerLayout.closeDrawer(Gravity.RIGHT);
} else {
mDrawerLayout.openDrawer(Gravity.RIGHT);
}
}
return true;
}
and menu.xml is
<?xml version="1.0" encoding="utf-8"?>
<item
android:id="#+id/toggle"
android:icon="#drawable/menu"
android:orderInCategory="100"
android:title="menutoggle"/>

In your xml, you can include this in each item you want to be clickable:
android:onClick="aRandomMethod"
Then in your activity, you must implement a method that supports the click, in this case, a method called aRandomMethod, like this:
public void aRandomMethod(MenuItem item){
/// stuff to do when you click in the button
}
If you want your icon to be always displayed in the action bar, add:
android:showAsAction="always"
The onOptionsItemSelected method that you have in your code is when you have the settings icon (three small dots) and then a submenu in the icon; is to handle the submenu.

Related

Change Item title OnMenuItemClick programmatically

I've set up a popup menu and setted an onMenuItemClickListener all fine, I want to have a 'Block' item in the menu and when clicked it should change its title (or set visibility to gone) to 'Unblock', I'll be grateful for any help .
In the onMenuItemClickListener method you should write following piece of code and you're done.
if(item.getVisibility==View.VISIBLE) {
item.setVisibility(View.GONE)
} else {
item.setVisibility(View.VISIBLE)
}
Support that you have a menu file in res/menu folder.
main_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/item_block"
android:title="Block"/>
</menu>
MainActivity.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_block:
// Set title to "Unblock"
item.setTitle("UnBlock");
// Or set visibility to GONE
// item.setVisible(false);
return true;
default:
return super.onOptionsItemSelected(item);
}
}

How to add progress bar icon in action bar?

How I can attach icon of progress bar to action bar that display loading process of some Internet data?
For example:
And icon while load data
First of all you have to create a custom menu to use inside your activity.
Secondly, you have to request the feature of progress bar inside your "onCreate".
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
// rest of your code
[....]
}//end of onCreate
Then your my_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_refresh"
android:icon="# drawable/ic_menu_refresh "
android:orderInCategory="100"
android:showAsAction="always"
android:title="Refresh"
android:visible="true"/>
</menu>
Back to your activity, you have to inflate this menu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_refresh:
// refresh icon clicked
//show the indeterminate progress bar
setSupportProgressBarIndeterminateVisibility(true);
// Rest of your code to do re refresh here
[...]
default:
return super.onOptionsItemSelected(item);
}
}
PS: All the above code is working using the ActionBar Compat Library.
EDIT:
Ok, to hide the action bar icon do this:
-Create a menuitem outside your functions:
MenuItem refreshIcon;
Edit your onCreateOptionsMenu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
//Initializing menu item
refreshIcon = menu.findItem(R.id.action_refresh);
return super.onCreateOptionsMenu(menu);
}
Then when you press the button change the visibility:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_refresh:
// refresh icon clicked
//show the indeterminate progress bar
setSupportProgressBarIndeterminateVisibility(true);
//hiding action icon
refreshIcon.setVisible(false);
// Rest of your code to do re refresh here
[...]
default:
return super.onOptionsItemSelected(item);
}
}
Finally, when your data is finished updating set the visibility to "true" and hide progressbar:
[...] //progress inside your AsyncTask or wherever you have your update
//show Refresh Icon again
refreshIcon.setVisible(true);
//hide the indeterminate progress bar
setSupportProgressBarIndeterminateVisibility(true);

Hide/Show Action Bar Option Menu Item for different fragments

I have a Sherlock Fragment Activity in which there are 3 Fragments.
Fragment A, Fragment B, Fragment C are three fragments. I want to show a done option menu in Fragment B only.
And the activity is started with Fragment A. When Fragment B is selected done button is added.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if(!menusInflated){
inflater.inflate(R.menu.security, menu);
menusInflated=true;
}
super.onCreateOptionsMenu(menu, inflater);
}
When I again start Fragment A I want to options Menu DONE (which was set at Fragment B) for this I am doing like this
setHasOptionsMenu(false);
MenuItem item = (MenuItem) menu.findItem(R.id.done_item);
item.setVisible(false);
But this is not hiding at all, also it is giving NullPointerException when Activity if first started with Fragment A.
Please let me know what is the problem.
Try this...
You don't need to override onCreateOptionsMenu() in your Fragment class again. Menu items visibility can be changed by overriding onPrepareOptionsMenu() method available in Fragment class.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_search).setVisible(false);
super.onPrepareOptionsMenu(menu);
}
This is one way of doing this:
add a "group" to your menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<group
android:id="#+id/main_menu_group">
<item android:id="#+id/done_item"
android:title="..."
android:icon="..."
android:showAsAction="..."/>
</group>
</menu>
then, add a
Menu menu;
variable to your activity and set it in your override of onCreateOptionsMenu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
// inflate your menu here
}
After, add and use this function to your activity when you'd like to show/hide the menu:
public void showOverflowMenu(boolean showMenu){
if(menu == null)
return;
menu.setGroupVisible(R.id.main_menu_group, showMenu);
}
I am not saying this is the best/only way, but it works well for me.
To show action items (action buttons) in the ActionBar of fragments where they are only needed, do this:
Lets say you want the save button to only show in the fragment where you accept input for items and not in the Fragment where you view a list of items, add this to the OnCreateOptionsMenu method of the Fragment where you view the items:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.findItem(R.id.action_save_item).setVisible(false);
}
}
NOTE: For this to work, you need the onCreate() method in your Fragment (where you want to hide item button, the item view fragment in our example) and add setHasOptionsMenu(true) like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Might not be the best option, but it works and it's simple.
This will work for sure I guess...
// Declare
Menu menu;
MenuItem menuDoneItem;
// Then in your onCreateOptionMenu() method write the following...
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
this.menu=menu;
inflater.inflate(R.menu.secutity, menu);
}
// In your onOptionItemSelected() method write the following...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.done_item:
this.menuDoneItem=item;
someOperation();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Now Making invisible any menu item...
public void menuInvisible(){
setHasOptionsMenu(true);// Take part in populating the action bar menu
menuDoneItem=(MenuItem)menu.findItem(R.id.done_item);
menuRefresh.setVisible(false); // make true to make the menu item visible.
}
//Use the above method whenever you need to make your menu item visible or invisiable
You can also refer this link for more details, it is a very useful one.
MenuItem Import = menu.findItem(R.id.Import);
Import.setVisible(false)
Try this
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.custom_actionbar, menu);
menu.setGroupVisible(...);
}
By setting the Visibility of all items in Menu, the appbar menu or overflow menu will be Hide automatically
Example
private Menu menu_change_language;
...
...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
...
...
menu_change_language = menu;
menu_change_language.findItem(R.id.menu_change_language).setVisible(true);
return super.onCreateOptionsMenu(menu);
}
Before going to other fragment use bellow code:
if(menu_change_language != null){
menu_change_language.findItem(R.id.menu_change_language)
.setVisible(false);
}
Hello I got the best solution of this, suppose if u have to hide a particular item at on create Menu method and show that item in other fragment. I am taking an example of two menu item one is edit and other is delete. e.g menu xml is as given below:
sell_menu.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/action_edit"
android:icon="#drawable/ic_edit_white_shadow_24dp"
app:showAsAction="always"
android:title="Edit" />
<item
android:id="#+id/action_delete"
android:icon="#drawable/ic_delete_white_shadow_24dp"
app:showAsAction="always"
android:title="Delete" />
Now Override the two method in your activity & make a field variable mMenu as:
private Menu mMenu; // field variable
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.sell_menu, menu);
this.mMenu = menu;
menu.findItem(R.id.action_delete).setVisible(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_delete) {
// do action
return true;
} else if (item.getItemId() == R.id.action_edit) {
// do action
return true;
}
return super.onOptionsItemSelected(item);
}
Make two following method in your Activity & call them from fragment to hide and show your menu item. These method are as:
public void showDeleteImageOption(boolean status) {
if (menu != null) {
menu.findItem(R.id.action_delete).setVisible(status);
}
}
public void showEditImageOption(boolean status) {
if (menu != null) {
menu.findItem(R.id.action_edit).setVisible(status);
}
}
That's Solve from my side,I think this explanation will help you.
You can make a menu for each fragment, and a global variable that mark which fragment is in use now.
and check the value of the variable in onCreateOptionsMenu and inflate the correct menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (fragment_it == 6) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.custom_actionbar, menu);
}
}
Okay I spend couple of hour to get this solution.apparently you can get menuitem from your toolbar to anywhere in activity or fragment. So in my case.
var menuItem = toolbar.menu;
Now to get specfic item from menu item
favIcon = menuItem.findItem(R.id.favourite);
Note: favIcon is MenuItem declare global
Now if you can do whatever you want to do for this icon
eg. to make it invisible
favIcon?.isVisible=false
Even though the question is old and answered. There is a simpler answer to that than the above mentioned. You don't need to use any other variables.
You can create the buttons on action bar whatever the fragment you want, instead of doing the visibility stuff(show/hide).
Add the following in the fragment whatever u need the menu item.
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
Sample menu.xml file:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_addFlat"
android:icon="#drawable/add"
android:showAsAction="ifRoom|withText"
android:title="#string/action_addFlat"/>
</menu>
Handling onclick events is as usual.
Late to the party but the answers above didn't seem to work for me.
My first tab fragment (uses getChildFragmentManager() for inner tabs) has the menu to show a search icon and uses android.support.v7.widget.SearchView to search within the inner tab fragment but navigating to other tabs (which also have inner tabs using getChildFragmentManager()) would not remove the search icon (as not required) and therefore still accessible with no function, maybe as I am using the below (ie outer main tabs with each inner tabs)
getChildFragmentManager();
However I use the below in my fragments containing/using the getChildFragmentManager() for inner tabs.
//region onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
//access setHasOptionsMenu()
setHasOptionsMenu(true);
}
//endregion onCreate
and then clear the menu item inside onPrepareOptionsMenu for fragments(search icon & functions)
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
//clear the menu/hide the icon & disable the search access/function ...
//this will clear the menu entirely, so rewrite/draw the menu items after if needed
menu.clear();
}
Works well and navigating back to the tab/inner tab with the search icon functions re displays the search icon & functions.
Hope this helps...
For some reason the method was not working for me this is how I solved it according to the accepted solution
//This should be in on create
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showOverflowMenu(false);
}
},100);
#Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}
public void showOverflowMenu(boolean showMenu){
if(menu == null)
return;
menu.setGroupVisible(R.id.grp, showMenu);
}

Android ActionBar Search Field

I have a standard search EditText in my ActionBar, triggered by a touch on a little magnifying glass icon. I can cache the user's search string using the OnQueryTextListener. I want to put that string back into the EditText when the user touches the icon a second time.
I'm using ABS (soon to abandon), targeting 8-19.
How can I do this?
With a normal action bar (you'll have to find the different variation with ABS, not sure if my answer will apply completely with that library).
SearchView is a widget that can be inflated in the options menu, so what I do is inflate a menu using an XML containing an action view:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/search_user"
android:actionViewClass="android.widget.SearchView"
android:icon="#drawable/magnifing_glass"
android:showAsAction="ifRoom|collapseActionView"
android:title="Search Users"/>
</menu>
Next, when inflating the action view, set your listeners, and use a global variable to save the previous search.
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu, menu);
MenuItem search = menu.findItem(R.id.search_user);
//Keep a global variable of this so you can set it within the next listener
SearchView user_search = (SearchView) search.getActionView();
user_search.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
global_variable = query;
return true;
}
#Override
public boolean onQueryTextChange(String text) {
return true;
}
});
Finally, in a second listener, set the text of the global variable to your previous query when the action view expands.
//This is set on the menu item
search.setOnActionExpandListener(new OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
user_search.setQuery(global_variable, false);
return true; // Return true to expand action view
}
});

android Setonclicklistener doesn't work with menu's items

i have a menu that contains just one item.
Button exit;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.exitmenu, menu);
return true;
}
exit=(Button)findViewById(R.id.bexitMenuExit);
if i add listener to exit button , i got excpetion (null pointer), i am sure that there is no syntax error, the button exit is comming from this menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/bexitMenuExit"
android:title="Exit"
android:icon="#android:drawable/ic_menu_close_clear_cancel"
></item>
</menu>
what am i doing wrong?
There is no need to initialize Button and this doesn't make sence for me.
Just inflate your Menu and just override onOptionsItemSelected method:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplicationContext()).inflate(R.menu.exitmenu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getId()) {
case R.id.bexitMenuExit:
// work that will start when you click on this
...
}
}
Also, there is no need to use OnClickListener, for this there is onOptionsItemSelected method and you should use it.
for menu items, as stated by Sajmon, you can use onOptionsIemsSelected function. onClickListener is used by views while this function has been designed to be used specifically by menu items using switch case.

Categories

Resources