SlidingMenu lib and ActionBarSherlock with uiOptions = splitActionBarWhenNarrow - android

everyone!
I'm using SlidingMenu library with ActionBarSherlock. When I setup uiOptions to splitActionBarWhenNarrow, ActionItems from bottombar are not clicable. This problem is reproduced only on android v2.3 and less. I think that SlidingMenu intercepts touch on ActionItem in the bottombar. If I touch on ActionItem and slide SlidingMenu, ActionItem becomes selected. I try to add actionItem as ignored to SlidingMenu, but it doesn't help:(
This is example of my code:
public class ExampleFragment extends BaseFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_positions, null);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
((BaseActivity)getActivity()).getSlidingMenu().clearIgnoredViews();
final SubMenu deal = menu.addSubMenu(R.string.deal).setIcon(R.drawable.ic_actionbar_deal);
deal.add(1, R.string.close_position, 0, R.string.close_position);
deal.add(1, R.string.open_position, 0, R.string.open_position);
final MenuItem dealItem = deal.getItem();
dealItem.setIcon(R.drawable.ic_actionbar_deal);
dealItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
final SubMenu edit = menu.addSubMenu(R.string.change).setIcon(R.drawable.ic_actionbar_edit);
edit.add(2, R.string.change_limitation, 0, R.string.change_limitation);
final MenuItem editItem = edit.getItem();
editItem.setIcon(R.drawable.ic_actionbar_edit);
editItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
if(DataContext.getInstance().getOpenPositions().size() == 0){
menu.findItem(R.string.close_position).setEnabled(false);
menu.findItem(R.string.change_limitation).setEnabled(false);
}
menu.add(0, R.string.reports, 0, R.string.reports).setIcon(R.drawable.ic_actionbar_report_stub).
setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
ignoreMenuItems(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.string.open_position:
Log.v(TAG, "onOptionsItemSelected open_position");
break;
case R.string.close_position:
Log.v(TAG, "onOptionsItemSelected close_position");
break;
case R.string.change_limitation:
Log.v(TAG, "onOptionsItemSelected change_limitation");
break;
case R.string.reports:
Log.v(TAG, "onOptionsItemSelected reports");
break;
}
return true;
}
public void ignoreMenuItems(Menu menu){
for(int i = 0; i < menu.size(); i++){
final MenuItem item = menu.getItem(i);
View view = getActivity().getLayoutInflater().inflate(R.layout.layout_action_view, null);
((ImageView) view.findViewById(R.id.action_view_image)).setImageDrawable(item.getIcon());
if(item.getSubMenu() != null){
item.getSubMenu().setHeaderView(view);
} else {
item.setActionView(view);
view.setLongClickable(true);
view.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
onOptionsItemSelected(item);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Toast.makeText(getActivity(), item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
}
((BaseActivity)getActivity()).getSlidingMenu().addIgnoredView(view);
}
}
Any ideas?

Related

android fragment action bar menu

I have created a fragment with action bar menu, that menu was shown but not working when its clicked.
Here is My Fragment:
public class ComposeFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_compose, container, false);
userName = (TextView) view.findViewById(R.id.user_name);
subjectSpinner = (Spinner) view.findViewById(R.id.subject_spinner);
sendButton = (Button) view.findViewById(R.id.send_btn);
messageEditText = (EditText) view.findViewById(R.id.message);
userName.setText(Ezcation.getInstance().userName);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.compose_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.e("Menu","Before Switch");
switch (item.getItemId()){
case R.id.sent:
Log.e("Menu","Sent");
if (messageEditText.getText().toString().equals("")){
messageEditText.setError("Please Enter your Message");
}else {
sendMessage(messageEditText.getText().toString());
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.messageActivity = (MessageActivity) context;
SpannableString s = new SpannableString("Compose Message");
s.setSpan(new TypefaceSpan(messageActivity, "Miller-Text.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
messageActivity.setTitle(s);
}
}
When menu was clicked even Log.e("Menu","Before Switch"); not working.
My Menu xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/sent"
android:title="Sent"
android:orderInCategory="10"
android:icon="#drawable/sent"
app:showAsAction="ifRoom" />
</menu>
For Future visiters you should use this in Activity class:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
To work properly hardcoding false isnt the right way
add this in your Activity.
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);;
}
The super call is missing inside onCreateOptionsMenu
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.compose_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}

How can I dynamically create menu items?

I'm building an Android application and I'm trying to build a user management system where users can login, logout, etc. I want to display a login menu item if the user is logged out and a logout button if the user is logged in. How can I do this dynamically?
This is the layout file right now:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/add" android:title="Add" android:icon="#drawable/ic_menu_add"/>
<item android:id="#+id/list" android:title="List" android:icon="#drawable/ic_menu_list"/>
<item android:id="#+id/refresh" android:title="Refresh" android:icon="#drawable/ic_menu_refresh"/>
<item android:id="#+id/login" android:title="Login" android:icon="#drawable/ic_menu_login"/>
</menu>
This is my Java right now:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.activity_main, menu);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
System.out.println(item.getItemId()==R.id.add);
if (item.getItemId()==R.id.add)
{
//Cannot add spot unless we have obtained the users current location.
if((currentLat != 0) && (currentLng != 0))
{
System.out.println("loggedin? : " + auth.isLoggedIn());
if(!auth.isLoggedIn())
{
Toast.makeText(MainActivity.this, "You must be logged in to add a new spot",
Toast.LENGTH_LONG).show();
}
else
{
Intent addIntent = new Intent(MainActivity.this, AddSpot.class);
Bundle b = new Bundle();
b.putDouble("currentLat", currentLat);
b.putDouble("currentLng", currentLng);
addIntent.putExtras(b);
startActivity(addIntent);
return(true);
}
}
}
else if(item.getItemId()==R.id.list)
{
//Pointless showing them a blank screen if nothing is retrieved from the server
if(list != null)
{
Intent listIntent = new Intent(MainActivity.this, ListLocations.class);
listIntent.putExtra("list", list);
startActivity(listIntent);
return(true);
}
}
if(item.getItemId()==R.id.refresh)
{
finish();
startActivity(getIntent());
return(true);
}
if(item.getItemId()==R.id.login)
{
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
return(true);
}
return(super.onOptionsItemSelected(item));
}
How to Dynamically Add Menu Items to an Android Activity
public class yourActivity extends Activity {
...
private static final int MENU_ADD = Menu.FIRST;
private static final int MENU_LIST = MENU.FIRST + 1;
private static final int MENU_REFRESH = MENU.FIRST + 2;
private static final int MENU_LOGIN = MENU.FIRST + 3;
/**
* Use if your menu is static (i.e. unchanging)
*/
/*
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_ADD, Menu.NONE, R.string.your-add-text).setIcon(R.drawable.your-add-icon);
menu.add(0, MENU_LIST, Menu.NONE, R.string.your-list-text).setIcon(R.drawable.your-list-icon);
menu.add(0, MENU_REFRESH, Menu.NONE, R.string.your-refresh-text).setIcon(R.drawable.your-refresh-icon);
menu.add(0, MENU_LOGIN, Menu.NONE, R.string.your-login-text).setIcon(R.drawable.your-login-icon);
return true;
}
*/
/**
* Gets called every time the user presses the menu button.
* Use if your menu is dynamic.
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if(enableAdd)
menu.add(0, MENU_ADD, Menu.NONE, R.string.your-add-text).setIcon(R.drawable.your-add-icon);
if(enableList)
menu.add(0, MENU_LIST, Menu.NONE, R.string.your-list-text).setIcon(R.drawable.your-list-icon);
if(enableRefresh)
menu.add(0, MENU_REFRESH, Menu.NONE, R.string.your-refresh-text).setIcon(R.drawable.your-refresh-icon);
if(enableLogin)
menu.add(0, MENU_LOGIN, Menu.NONE, R.string.your-login-text).setIcon(R.drawable.your-login-icon);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case MENU_ADD: doAddStuff(); break;
case MENU_LIST: doListStuff(); break;
case MENU_REFRESH: doRefreshStuff(); break;
case MENU_LOGIN: doLoginStuff(); break;
}
return false;
}
The following specific example adds a MENU_LOGOUT option if the user is logged in.
private static final int MENU_LOGOUT = MENU.FIRST + 4;
public boolean onPrepareOptionsMenu(Menu menu) {
...
if(auth.isLoggedIn()) {
menu.add(0, MENU_LOGOUT, Menu.NONE, R.string.your-logout-text).setIcon(R.drawable.your-logout-icon);
}
...
}
public boolean onOptionsItemSelected(MenuItem item) {
...
case MENU_LOGOUT:
if(auth.isLoggedIn()) {
doLogout();
} else {
Toast.makeText(this, "You must have somehow been logged out between the time the menu button was pressed and now.", Toast.DURATION_LONG).show();
}
break;
...
}
That's all there is to it.
In my case the menu items are in the ArrayList , - try this Hope it will help u :)
public void onClick(View v)
{
PopupMenu menu = new PopupMenu(DialogCheckBox.this, v);
for (String s : limits) { // "limits" its an arraylist
menu.getMenu().add(s);
}
menu.show();
}
you can call invalidateOptionsMenu() (note:need to use compatability library like actionBarSherlock to access in case you need to support low API versions) , and then update the menu items according to the status.
there you could hide the login action item and show the logout action item.
you might also try update the icon itself but i never tried it.
private void getPopup(final TextView textView, ArrayList<String> arrayList) {
final PopupMenu popupMenu = new PopupMenu(sContext, textView);
for (int i = 0; i < arrayList.size(); i++) {
popupMenu.getMenu().add(arrayList.get(i));
}
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
textView.setText(item.getTitle());
return false;
}
});
popupMenu.show();
}
Simple way to create menu items :
Dynamic_PopUpMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu menu = new PopupMenu(DialogCheckBox.this, v);
menu.getMenu().add("AGIL"); // menus items
menu.getMenu().add("AGILANBU"); // menus items
menu.getMenu().add("AGILarasan");
menu.getMenu().add("Arasan");
menu.show();
}
});
Try this :)
it's so easy
To create the menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
for (int i = 0; i < list.size(); i++) {
menu.add(0, i, 0, "Menu Name").setShortcut('5', 'c');
}
return true;
}
to get the details from clicked menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); //to get the selected menu id
String name = item.getTitle(); //to get the selected menu name
return super.onOptionsItemSelected(item);
}

onContextItemSelected called twice for fragment

My app has a ListView and I'm using a Contextual Action Bar for devices above SDK 11 and the old popup contextual actions for older devices. I know there's a way to use a CAB with older devices but I tried to implement it and found it wasn't worth the effort for devices that will eventually be obsolete. I know it's some code duplication, but, in theory, I will be getting rid of the old popup actions (emphasis on "in theory").
Anyhow, when I use the emulator, the CAB works fine, but the old popup actions for older devices seems to hit onContextItemSelected twice when I put a breakpoint in that event. I've just start implement a ViewPager for my app and this wasn't happening before the ViewPager so not sure if that is causing the issue.
This is the code I'm using:
public class MyFragment extends SherlockListFragment
{
private ListView mListView;
private android.view.ActionMode mActionMode;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
if (this.mActionMode != null) return;
menu.add(1, 0, 0, "Delete");
menu.add(1, 1, 0, "Save");
}
#Override
public void onActivityCreated(final Bundle icicle)
{
mListView = getListView();
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
{
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onCreateActionMode(android.view.ActionMode mode, android.view.Menu menu) {
// Inflate the menu for the CAB
menu.clear();
menu.add(1, 1, 2, "Delete").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(1, 3, 1, "Save").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
#Override
public boolean onActionItemClicked(android.view.ActionMode mode, android.view.MenuItem item) {
mActionMode = mode;
if (item.getGroupId() == 1)
{
switch(itemId)
{
case 0:
DeleteItem();
break;
case 1:
SaveItem();
break;
}
}
}
}
}
}
#Override
public boolean onContextItemSelected(final android.view.MenuItem item) {
if (item.getGroupId() == 1) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
final Integer position = info.position;
final int itemId = item.getItemId();
switch(itemId)
{
case 0:
DeleteItem();
break;
case 1:
SaveItem();
break;
}
}
return super.onContextItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu (menu);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.my_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
ViewPager code
public class Main extends SherlockFragmentActivity
{
private static List<Integer> mIds;
#Override
public void onCreate(final Bundle icicle)
{
super.onCreate(null);
setContentView(R.layout.main);
mViewPager = (ViewPager)findViewById(R.id.viewpager); //view pager exists, so we are using the portait layout
if (mViewPager != null)
{
mIds = new ArrayList<Integer>();
mIds.add(0);
mIds.add(1);
mIds.add(2);
}
else //in landscape
{
ListFragment lf = (ListFragment)getSupportFragmentManager().findFragmentById(R.id.fragmentList);
if (lf == null)
lf = new ListFragment();
DetailFragment df = (DetailFragment)getSupportFragmentManager().findFragmentById(R.id.fragmentDetail);
if (df == null)
{
df = new DetailFragment();
df.setArguments(getIntent().getExtras());
}
getSupportFragmentManager().beginTransaction().add(R.id.fragmentList, lf).commit();
getSupportFragmentManager().beginTransaction().add(R.id.fragmentDetail, df).commit();
}
}
private static class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
//can't use getSupportFragmentManager().findFragmentById() here because I get a "Cannot make a static reference to the non-static method" error
if (index == 0)
return ListFragment.newInstance();
else
return DetailFragment.newInstance(mIds.get(index-1));
}
#Override
public int getCount() {
return 4;
}
}
}
This solution on this question fixed my issue:
How to handle onContextItemSelected in a multi fragment activity?
using getUserVisibleHint() in onContextItemSelected.
Method must return true to consume the selection.
Docs here
#Override
public boolean onContextItemSelected(final android.view.MenuItem item) {
if (item.getGroupId() == 1) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
final Integer position = info.position;
final int itemId = item.getItemId();
switch(itemId)
{
case 0:
DeleteItem();
return true;
case 1:
SaveItem();
return true;
}
}
return super.onContextItemSelected(item);
}

Android ActionBar Action Items

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.

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