Android ActionBar Action Items - android

I am using Actionbar Sherlock and and i have three buttons
Search with a SearchView
Categories which opens a Dialog Fragment
Sort which opens a hiddent drop down menu
When i click the Search Button the SearchView text expands. When the Search view has expanded i want to hide all the other icons from the action bar and it should return when i exit the expanded searchView mode.
public class MainActivity extends SherlockFragmentActivity implements
SearchView.OnQueryTextListener {
protected static CharSequence[] _categories = { "Amusement Park",
"Bird Sanctuary", "Wild Life", "River", "Hill Station", "Temple" };
protected static boolean[] _selections = new boolean[_categories.length];
public SearchView mSearchView;
private TextView mStatusView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
MenuItem categoryItem = menu.findItem(R.id.action_category);
MenuItem sortItem = menu.findItem(R.id.action_sort);
mSearchView = (SearchView) searchItem.getActionView();
setupSearchView(searchItem, categoryItem, sortItem);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/*
* case R.id.action_go: Intent i = new Intent(MainActivity.this,
* PlaceActivity.class); startActivity(i); break;
*/
/*
* case R.id.action_search: Toast.makeText(this, "Searh",
* Toast.LENGTH_LONG).show(); break;
*/
case R.id.action_category:
showDialog();
break;
case R.id.action_sort_alpha_az:
Toast.makeText(this, "Alpha AZ", Toast.LENGTH_LONG).show();
break;
case R.id.action_sort_alpha_za:
Toast.makeText(this, "Alpha ZA", Toast.LENGTH_LONG).show();
break;
case R.id.action_sort_dist_nf:
Toast.makeText(this, "Dist NF", Toast.LENGTH_LONG).show();
break;
case R.id.action_sort_dist_fn:
Toast.makeText(this, "Dist FN", Toast.LENGTH_LONG).show();
break;
default:
// return super.onOptionsItemSelected(item);
break;
}
return true;
}
private void setupSearchView(MenuItem searchItem, MenuItem categoryItem,
MenuItem sortItem) {
mSearchView.setIconifiedByDefault(true);
searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
public boolean onQueryTextChange(String newText) {
Log.i("Nomad", "onQueryTextChange");
return false;
}
public boolean onQueryTextSubmit(String query) {
Log.i("Nomad", "onQueryTextSubmit");
return false;
}
public boolean onClose() {
Log.i("Nomad", "onClose");
return false;
}
protected boolean isAlwaysExpanded() {
return false;
}
}

I'm doing the same as follows:
private Menu mainMenu = null;
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
mainMenu = menu;
MenuItem searchItem = menu.findItem(R.id.action_search);
MenuItem categoryItem = menu.findItem(R.id.action_category);
MenuItem sortItem = menu.findItem(R.id.action_sort);
mSearchView = (SearchView) searchItem.getActionView();
mSearchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//hide action item
if (mainMenu != null)
mainMenu.findItem(R.id.quick_actions).setVisible(false);
}
});
mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
//re-show the action button
if (mainMenu != null)
mainMenu.findItem(R.id.quick_actions).setVisible(true);
return false;
}
});
//setupSearchView(searchItem, categoryItem, sortItem);
return true;
}

My solution is:
#Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater)
{
final MenuItem item = menu.add(0, MENU_SEARCH, 0, "Search");
final SearchView searchView = new SearchView(getActivity());
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener()
{
#Override
public void onFocusChange(View view, boolean queryTextFocused)
{
if(!queryTextFocused)
{
item.collapseActionView();
}
int count = menu.size();
for (int i = 0; i < count; i ++)
{
MenuItem it = menu.getItem(i);
it.setVisible(item.equals(it)) || !queryTextFocused);
}
}
});
item.setActionView(searchView);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}

Simply on the xml of menu, just give the attribute as app:showAsAction="collapseActionView|ifRoom" for seachview and to other menu items give it as app:showAsAction="ifRoom".This will give you the expected result.

Related

How to set visibility of one menu item false after clicking on another menu item

I am trying to set visibility of SaveMessage true after clicking on UnsaveMessage and visibility of Unsavemessage false but i only see on item and nothing happens on Onclick
My code
private boolean isEditing = true;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_message,menu);
menu.findItem(R.id.UnsavedMessage).setVisible(isEditing);
menu.findItem(R.id.SaveMessage).setVisible(!isEditing);
return super.onCreateOptionsMenu(menu);
}
#Override
public void supportInvalidateOptionsMenu() {
super.supportInvalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == R.id.UnsavedMessage){
isEditing=false;
}
if (item.getItemId()==R.id.SaveMessage){
isEditing=true;
}
return true;
}
You need to do this
private boolean isEditing = true;
private MenuItem unSavedMsg;
private MenuItem SaveMsg;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_message,menu);
unSavedMsg = menu.findItem(R.id.UnsavedMessage)
unSavedMsg .setVisible(isEditing);
saveMsg = menu.findItem(R.id.SaveMessage)
saveMsg .setVisible(!isEditing);
return super.onCreateOptionsMenu(menu);
}
#Override
public void supportInvalidateOptionsMenu() {
super.supportInvalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == R.id.UnsavedMessage){
isEditing=false;
// Show/Hide Btn here
unSavedMsg.setVisibility(false)
saveMsg.setVisibility(true)
}
if (item.getItemId()==R.id.SaveMessage){
isEditing=true;
// Show/Hide Btn here
unSavedMsg.setVisibility(true)
saveMsg.setVisibility(false)
}
return true;
}

hide/show options menu when clicking buttons

I'm using some buttons in my fragments. When i checks those buttons then options menu should display. And when i uncheck it it should hide options menu. How should i do this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mLocation = getArguments().getString(Beco.EXTRA_LOCATION);
listMalls = temporaryModelCache.getDealData().getFacets().getArea();
listCategories = temporaryModelCache.getDealData().getFacets().getCategories();
listGender = temporaryModelCache.getDealData().getFacets().getAgeGroup();
try {
MainActivity activity = (MainActivity) getActivity();
if (activity != null) activity.hideBottomBar();
} catch (Exception ignored) {
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.forgot_password, menu);
mResetButton = menu.findItem(R.id.action_reset);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.action_reset:
Log.d(TAG, "onClick");
resetFilter();
return true;
}
return super.onOptionsItemSelected(item);
}
And this is the event that i need to hide/display options menu
private void checkSelected() {
if (!mapMall.isEmpty() || !mapGender.isEmpty() || !mapCategory.isEmpty()) {
footerTab.setVisibility(View.VISIBLE);
} else {
footerTab.setVisibility(View.GONE);
}
}
When if (!mapMall.isEmpty() || !mapGender.isEmpty() || !mapCategory.isEmpty()) i need to display actions menu and in the else part i need to hide options menu ! How can i achieve this?
call invalidateOptionsMenu() for hide and show option menu
Boolean Isreset= false;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.forgot_password, menu);
mResetButton = menu.findItem(R.id.action_reset);
if(!Isreset)
{
mResetButton.setVisibility(true);
}else{
mResetButton.setVisibility(false);
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.action_reset:
Log.d(TAG, "onClick");
resetFilter();
Isreset= true;
invalidateOptionsMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
You can keep the instance of Menu object and later on use it to invalidate the options menu.
private Menu menu;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mLocation = getArguments().getString(Beco.EXTRA_LOCATION);
listMalls = temporaryModelCache.getDealData().getFacets().getArea();
listCategories = temporaryModelCache.getDealData().getFacets().getCategories();
listGender = temporaryModelCache.getDealData().getFacets().getAgeGroup();
try {
MainActivity activity = (MainActivity) getActivity();
if (activity != null) activity.hideBottomBar();
} catch (Exception ignored) {
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.forgot_password, menu);
mResetButton = menu.findItem(R.id.action_reset);
this.menu = menu;
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.action_reset:
Log.d(TAG, "onClick");
resetFilter();
return true;
}
return super.onOptionsItemSelected(item);
}
Using the menu object then toggle the options menu.
private void checkSelected() {
if (!mapMall.isEmpty() || !mapGender.isEmpty() || !mapCategory.isEmpty()) {
footerTab.setVisibility(View.VISIBLE);
menu.findItem(R.id.action_reset).setVisibility(View.VISIBLE);
} else {
footerTab.setVisibility(View.GONE);
menu.findItem(R.id.action_reset).setVisibility(View.GONE);
}
}

Android ActionBarSherlock, SearchView `setOnCloseListener` is not working

I am using SearchView and it is working fine but only setOnCloseListener is not working; Here is my code
import com.actionbarsherlock.widget.SearchView.OnCloseListener;
and
searchView.setOnCloseListener(new OnCloseListener() {
#Override
public boolean onClose() {
Toast.makeText(context, "close", Toast.LENGTH_SHORT).show();
return false;
}
});
**EDIT****
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Used to put dark icons on light action bar
//Create the search view
final SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
searchView.setQueryHint("Search");
searchView.setIconifiedByDefault(true);
//search button
menu.add(Menu.NONE,Menu.NONE,1,"Search a word")
.setIcon(R.drawable.abs__ic_search_api_holo_light)
.setActionView(searchView)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
MenuItem sView = menu.findItem(1);
sView.setOnActionExpandListener(this);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
adopter.getFilter().filter(null);
Toast.makeText(getApplicationContext(), "collapse", Toast.LENGTH_LONG).show();
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
Toast.makeText(getApplicationContext(), "Expand", Toast.LENGTH_LONG).show();
return true; // Return true to expand action view
}
Solved it by myself. Just leave setOnCloseListener it will not work, and put following code in onCreateOptionsMenu
// searchView.setOnCloseListener(new OnCloseListener() {
// #Override
// public boolean onClose() {
// adapter.getFilter().filter("");
// Toast.makeText(getBaseContext(), "on close", Toast.LENGTH_SHORT).show();
// return false;
// }
// });
MenuItem menuItem = menu.findItem(ID_OF_SEARCHVIEW);
menuItem.setOnActionExpandListener(new OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
adapter.getFilter().filter("");
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
adapter.getFilter().filter("");
return true;
}
});
I have encountered the same problem with onCloseListener not invoking for the SearchView.
Understand from the bug issue raised in 25758, and some postings I have read, to invoke onCloseListener, you need to set:
searchView.setIconifiedByDefault(true);
But for my case I wanted to have the search view opened & not iconified all the time. I manage to resolve this by adding one more line below:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_bar, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(queryTextListener);
searchView.setIconifiedByDefault(true);
searchView.setIconified(false);
return true;
}
The searchView.setIconified(false) will cause the searchView to open up, despite setting the default to iconified to true in the previous line. In this way, I managed to have both a SearchView
that opens up all the time & having it invoke the onCloseListener.
I'm using this code. And it works perfectly
#Override
public void onStartSearch() {
}
#Override
public void onSearch(String search) {
}
#Override
public void onCloseSearch() {
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.your_menu, menu);
// Associate searchable configuration with the SearchView
MenuItem searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem); //here I user appcompat, but you can take it just from actionbarsherlock
SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete) mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchAutoComplete.setTextColor(getResources().getColor(R.color.action_bar_text_color));
mSearchView.setIconifiedByDefault(true);
mSearchView.setSubmitButtonEnabled(false);
/**
* Set all of different kinds of listeners
*/
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
menuIsOpen = false;
onCloseSearch();
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
menuIsOpen = true;
onStartSearch();
return true;
}
});
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String s) {
onSearch(s);
return false;
}
#Override
public boolean onQueryTextSubmit(String s) {
onSearch(s);
return true;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
/**
* Function for closing search when android is less than 14
*/
public boolean onBackButton() {
if (AndroidUtils.getSdkVersion() >= 14)
return false;
if (menuIsOpen) {
menuIsOpen = false;
getActivity().supportInvalidateOptionsMenu();
onCloseSearch();
return true;
}
return false;
}
After backButton it close search, or just by selecting close from action bar.
You can use a OnActionExpandListener:
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
SearchView searchView = new SearchView(((SherlockFragmentActivity) getActivity()).getSupportActionBar().getThemedContext());
searchView.setIconifiedByDefault(true);
// ...
MenuItem menuItem = menu.add(R.string.search);
// ...
menuItem.setOnActionExpandListener(this);
}
#Override
public boolean onMenuItemActionExpand(final MenuItem item) {
mInSearchMode = true;
return true;
}
#Override
public boolean onMenuItemActionCollapse(final MenuItem item) {
mInSearchMode = false;
return true;
}

Android SearchView doesnt enter onQueryTextChange

I am trying to to implement SearchView with Sherlock Action Bar. I am not able to get the query to enter the onQueryTextChange method. Not sure whats going wrong.
public class MainActivity extends SherlockFragmentActivity implements
SearchView.OnQueryTextListener {
protected static CharSequence[] _categories = { "Amusement Park",
"Bird Sanctuary", "Wild Life", "River", "Hill Station", "Temple" };
protected static boolean[] _selections = new boolean[_categories.length];
private final String[] places = new String[] { "Mysore", "Bangalore",
"Mangalore", "Wayanad", "Bandipur National Park", "Chickmaglur",
"Bandipura", "Coorg", "Kodaikanal", "Hampi", "Ghati Subramanya",
"Mekedatu", "Muththathhi", "Shivasamudram", "Talakadu",
"Savana Durga" };
public SearchView mSearchView;
private TextView mStatusView;
private Menu mainMenu = null;
PlacesListAdapter adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("Nomad", "onCreate");
List<Place> thePlaces = new ArrayList<Place>();
for (int i = 0; i < places.length; i++) {
Place pl = new Place("NO_ID", places[i], "NO_DISTANCE",
"NO_CATEGORYICON");
thePlaces.add(pl);
}
listView = (ListView) findViewById(R.id.place_list);
adapter = new PlacesListAdapter(MainActivity.this, R.layout.item_place,
thePlaces);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "Test", Toast.LENGTH_SHORT);
startActivity(new Intent(MainActivity.this, PlaceActivity.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i("Nomad", "onCreateOptionsMenu");
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
mainMenu = menu;
MenuItem searchItem = menu.findItem(R.id.action_search);
// Search View
mSearchView = (SearchView) searchItem.getActionView();
setupSearchView(searchItem);
mSearchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// hide action item
if (mainMenu != null) {
mainMenu.findItem(R.id.action_category).setVisible(false);
mainMenu.findItem(R.id.action_sort).setVisible(false);
}
}
});
mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
// re-show the action button
if (mainMenu != null) {
mainMenu.findItem(R.id.action_category).setVisible(true);
mainMenu.findItem(R.id.action_sort).setVisible(true);
}
return false;
}
});
Log.i("Nomad", "after setupSearchView()");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(this, "Searh", Toast.LENGTH_LONG).show();
Log.i("Nomad", "Click Search");
break;
case R.id.action_category:
showDialog();
break;
case R.id.action_sort_alpha_az:
Toast.makeText(this, "Alpha AZ", Toast.LENGTH_LONG).show();
break;
case R.id.action_sort_alpha_za:
Toast.makeText(this, "Alpha ZA", Toast.LENGTH_LONG).show();
break;
case R.id.action_sort_dist_nf:
Toast.makeText(this, "Dist NF", Toast.LENGTH_LONG).show();
break;
case R.id.action_sort_dist_fn:
Toast.makeText(this, "Dist FN", Toast.LENGTH_LONG).show();
break;
default:
// return super.onOptionsItemSelected(item);
break;
}
return true;
}
private void setupSearchView(MenuItem searchItem) {
mSearchView.setIconifiedByDefault(true);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(false);
searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
// | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
}
public boolean onQueryTextChange(String newText) {
Log.i("Nomad", "onQueryTextChange");
if (TextUtils.isEmpty(newText)) {
Log.i("Nomad", "onQueryTextChange Empty String");
listView.clearTextFilter();
} else {
Log.i("Nomad", "onQueryTextChange " + newText.toString());
adapter.getFilter().filter(newText.toString());
}
return true;
}
public boolean onQueryTextSubmit(String query) {
Log.i("Nomad", "onQueryTextSubmit");
return false;
}
public boolean onClose() {
Log.i("Nomad", "onClose");
return false;
}
protected boolean isAlwaysExpanded() {
return false;
}
}
Add this to your searchCommand :
searchCommand.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

onOptionsItemSelected not called when using actionLayout (SherlockActionBar)

The method onOptionsItemSelected isn't being called when using actionLayout in a menu item.
Am I missing something, or is it a known problem with SherlockActionBar?
Activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.article, menu);
super.onCreateOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected()");
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.menu_item_comment:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Menu
<item android:id="#+id/menu_item_comment"
android:showAsAction="ifRoom"
android:actionLayout="#layout/action_bar_comment_layout"/>
well, you have to set onClickListener on that actionLayout to receive callback. I do it like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.map_menu, menu);
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
if (item.getItemId() == R.id.menu_more) {
itemChooser = item.getActionView();
if (itemChooser != null) {
itemChooser.setOnClickListener(this);
}
}
}
return super.onCreateOptionsMenu(menu);
}
You'll have to add your own OnClickListener and explicitly call onOptionsItemSelected:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem awesomeMenuItem = menu.findItem(R.id.action_awesome);
View awesomeActionView = menuItem.getActionView();
awesomeActionView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(awesomeMenuItem));
}
});
}
P.S: Don't know why it doesn't work out of the box.
You should use MenuItemCompat.getActionView(menuItem); instead of item.getActionView(); if you are developing for older version.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
for (int i = 0; i< menu.size() ;i++) {
MenuItem menuItem = menu.getItem(i);
if (menuItem.getItemId() == R.id.add_item) {
View view = MenuItemCompat.getActionView(menuItem);
if (view != null) {
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ToDoActivity.class);
startActivity(intent);
}
});
}
}
}
return true;
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_add_require, menu)
val menuItem = menu!!.findItem(R.id.menu_cart)
val view = menuItem.actionView
view.setOnClickListener {
onOptionsItemSelected(menuItem)
}
return true
}
Working for me (code is in kotlin)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
View view = menu.findItem(R.id.menu_item_comment).getActionView();
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something
}
});
return true;
}
Also, (and that was very important for me, so other answers did not work) you need to disable the clickable option of all views in your action layout (that is, action_bar_comment_layout.xml):
android:clickable="false"
Combining #Arun Kumar's and #Luten's answers, the below method will make the implementation generic. For all the menu items using actionView, we setOnClickListener to call onOptionsItemSelected(item).
This way we can mix and match normal and actionLayout menu items, without worrying about setting individual onClickListeners.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(menuResourceId(), menu);
for (int i = 0; i < menu.size(); i++) {
final MenuItem item = menu.getItem(i);
View actionView = MenuItemCompat.getActionView(item);
if (actionView != null) {
actionView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
onOptionsItemSelected(item);
}
});
}
}
super.onCreateOptionsMenu(menu, inflater);
}

Categories

Resources