Different views / styles for a specific menu item on an ActionBar

1 answer

So, I got this to work now with a little trick. Here is a snippet of code

@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menuItemCreateCart = menu.findItem(R.id.menuItemCreateCart); if (menuItemCreateCart == null) { menuItemCreateCart = menu.add(0, R.id.menuItemCreateCart, 0, R.string.Create); } TextView tv = new TextView(getActivity()); tv.setText(R.string.Create); tv.setTextColor(getResources().getColor(R.color.green)); tv.setBackgroundColor(getResources().getColor(R.color.lightBlue)); tv.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { createCart(); } } ); menuItemCreateCart.setActionView(tv); 

The main question is that onclicklistener should be installed on the view that you specify as the type of action, and not the menu item for it to work. This way you can do whatever you want.

Also note that you cannot use getActionView to retrieve the originally specified view with a title, because it will return null. This appears to be more of an alternative view than the actual default menu item view.

+12
source

Source: https://habr.com/ru/post/904279/


All Articles