Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the view from the action bar menu item

Tags:

android

I have a PopupWindow that I want to anchor to an action bar menu item but can't seem anyway to get at the View of the item that I want to click on. This is required for the PopupWindow showAsDropDown() method.

Does anyone know how to achieve this?

like image 261
Kyros Avatar asked Nov 12 '12 13:11

Kyros


People also ask

How do I get menu item view?

If you have access to and use AppCompat's Toolbar there is a way. It's not the most efficient way, but it's the easiest way I've found to access the menu item's view. public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { Toolbar toolbar = (Toolbar) view. findViewById(R.

Which method is used to create menu items on action bar?

The Android tooling automatically creates a reference to menu item entries in the R file, so that the menu resource can be accessed. An activity adds entries to the action bar in its onCreateOptionsMenu() method. The showAsAction attribute allows you to define how the action is displayed.

How to use action view in Android Studio?

To add an action view, create an <item> element in the toolbar's menu resource, as Add Action Buttons describes. Add one of the following two attributes to the <item> element: actionViewClass : The class of a widget that implements the action. actionLayout : A layout resource describing the action's components.


3 Answers

You can get the view using the menu item id, by getting it in onOptionsItemSelected ..

findViewById(R.id.menu_item);
like image 86
Nermeen Avatar answered Oct 25 '22 07:10

Nermeen


findViewById doesn't have to be run on onOptionsItemSelected in order to get the view of the action item.

however, do note that sometimes action items get to be inside the overflow menu so you might get a null instead.

so, how can you do it?

here's a sample code:

public boolean onCreateOptionsMenu(final Menu menu) {
  getSupportMenuInflater().inflate(R.menu.main, menu);
  new Handler().post(new Runnable() {
    @Override
    public void run() {
      final View menuItemView = findViewById(R.id.menu_action_item);
      ...

this was tested when using actionBarSherlock library, on android 4.1.2 and android 2.3.5 .

another alternative is to use a more extensive way , used on the showcaseView library, here .

like image 21
android developer Avatar answered Oct 25 '22 06:10

android developer


Every where call:

activity.findViewById(R.id.menu_item);

If your code inside fragment don't use:

getView().findViewById(R.id.menu_item); 

It will return null.

like image 2
Mahmoud Avatar answered Oct 25 '22 07:10

Mahmoud