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?
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.
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.
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.
You can get the view using the menu item id, by getting it in onOptionsItemSelected
..
findViewById(R.id.menu_item);
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With