Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Open menu programmatically

I've been trying to add a functionality to my android application such that when I click a button, menu listing should be visible:

Here is my code:

menu.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.example.MainActivity" >

    <item android:id="@+id/action_onthego_sentence"
          android:title="settings"
          android:orderInCategory="100"
          app:showAsAction="never" />

</menu>

From the main activity, upon clicking a button, I do:

        button.setOnClickListener( new View.OnClickListener()
        {
            @Override
            public void onClick( View view )
            {
                runOnUiThread( new Runnable()
                {
                    @Override
                    public void run()
                    {
                        openOptionsMenu();
                    }
                } );
            }
        } );

What I need is:

enter image description here

As shown in the image, I'd like to see the menu is opened. Any suggestions please?

like image 503
KTB Avatar asked Apr 28 '26 07:04

KTB


2 Answers

If you are using customized toolbar in your app, then the following way will be useful,

 new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    toolbar.showOverflowMenu();
                }
            }, 500);
like image 147
Nanda Gopal Avatar answered Apr 30 '26 20:04

Nanda Gopal


Hello Dear if you are using toolbar following code

toolbar.showOverflowMenu();

And other wise you can directly call

MainActivity.this.openOptionsMenu();
like image 29
Dhaval Solanki Avatar answered Apr 30 '26 19:04

Dhaval Solanki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!