Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a default selected option in Android popup menu?

I am using following code to create a menu:

    PopupMenu popup = new PopupMenu(getApplicationContext(), v);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.equalizer, popup.getMenu());
    popup.show();

equalizer.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item android:id="@+id/flat"
              android:title="Flat" />
        <item android:id="@+id/stadium"
              android:title="Stadium" />
        <item android:id="@+id/jazz"
              android:title="Jazz" />
         <item android:id="@+id/rock"
              android:title="Rock" />
         <item android:id="@+id/pop"
              android:title="Pop" />
    </group>
</menu>

How is it possible to set, let's say, 3rd option of the menu as selected by default?


EDIT: I would like to change defaults programmatically.

like image 203
Arturs Vancans Avatar asked Aug 23 '12 13:08

Arturs Vancans


3 Answers

Answers have been given for setting a checked item in xml. If you want to do it in code, use:

popup.getMenu().getItem(2).setChecked(true);

to select the 3rd item. After you inflated the menu of course...

like image 172
ekholm Avatar answered Oct 07 '22 21:10

ekholm


Set android:checked="true" in item which you want select default.

like image 37
Rajesh Rajaram Avatar answered Oct 07 '22 21:10

Rajesh Rajaram


<item android:id="@+id/jazz"
  android:title="Jazz"
  android:checked="true" />
like image 36
Alexis C. Avatar answered Oct 07 '22 22:10

Alexis C.