Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spinner in action bar with only icon but not the selected option

I am working on a app with action bar for navigation. Now I am trying to add a Spinner to the ActionBar.

I am able to get my custom icon on the ActionBar. But when I add entries into the spinner, the icon is hidden behind the selection box with first item selected.

I want to have only the icon in the ActionBar and the drop-down-list/spinner to appear when tapped on the icon.

This is my code :

private void initializeMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options, menu);

    View v = (View) menu.findItem(R.id.menuSort).getActionView();
    Spinner spinner=(Spinner)v.findViewById(R.id.bookmarks_menu);

    Bookmark bookmark1 = new Bookmark();
    Bookmark bookmark2 = new Bookmark();

    List<Bookmark> list = new ArrayList<Bookmark>();
    list.add(bookmark1);
    list.add(bookmark2);

    SpinAdapter adapter = new SpinAdapter(getApplicationContext(),0, list);
    spinner.setAdapter(adapter); 
}
like image 583
Vijay Anant Avatar asked Apr 24 '13 05:04

Vijay Anant


Video Answer


2 Answers

Icon-only Spinner is achievable through a few steps.

Step 1

Put the icon you want in the xml:

<Spinner
    ...
    android:background="@drawable/ic_sort_white_24dp" />

Step 2

Then, in the adapter of the Spinner, override getView(), like this:

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list){
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // this part is needed for hiding the original view
            View view = super.getView(position, convertView, parent);
            view.setVisibility(View.GONE);

            return view;
        }
};

Explanation

We need to understand that getView() in the adapter is the view that will be used when the Spinner is not opened. We make the visibility gone because we don't want to see it, so that what is left is the background of Spinner from the xml, which I already set to ic_sort_white_24dp in this example (Step 1).

Do not mix up with getDropDownView() which is used for the rows of options that will drop downed after the Spinner is clicked.

Bonus Screenshot!

This is how mine look like. Hope it helps!

screenshot

like image 187
I'm a frog dragon Avatar answered Oct 12 '22 10:10

I'm a frog dragon


In your adapter, you need to override getDropDownView(). That should provide the view used in the rows of the spinner. getView() should then return an ImageView for your icon.

See these 2 answers on similar questions for more details and examples:

  • actionbar spinner customization
  • difference between getview and getdropdownview
like image 1
John Avatar answered Oct 12 '22 10:10

John