1

I'm willing to add a Spinner that will open when I click on the Activity's title in the ActionBar (I don't use a Toolbar, I use the support ActionBar).

I tried with the method setListNavigationCallbacks(SpinnerAdapter adapter, ActionBar.OnNavigationListener callback) on the ActionBar. It works, but it displays the selected item next to the title.

Code of the Activity onCreate

actionBar.setTitle("Title");
actionBar.setNavigationMode(NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(spinnerAdapter, null);
// spinnerAdapter contains simply numbers from 1 to 10

I know that using these methods and using the support ActionBar instead of the Toolbar are deprecated, but changing the ActionBar by the Toolbar in my project will have huge impacts and I will have a lot of work to do...

I don't want to use any external library if possible, as this is obviously not very complicated to do.

Thank you!

Rohit Poudel
  • 1,793
  • 2
  • 20
  • 24
Youb
  • 93
  • 1
  • 10

1 Answers1

0

First, you have to create an xml file in res/menu/ folder and add a menu item with id, name, actionViewClass. Menu item file will look like below.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/spinner"
    android:title="ActionBar Spinner"
    app:actionViewClass="android.widget.Spinner"
    android:background="#ff00"
    app:showAsAction="always" />
</menu>

Open you java activity file, go to onCreateOptionMenu method if already have and if not then override new method called onCreateOptionMenu and link it to your spinner menu item file using getMenuInflater. And set adapter to the spinner menu item class. Java activity file will looks like below.

public class SpinnerAndroidActionBarToolBar extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.android_actionbar_toolbar_spinner_example_layout);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);
        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.spinner_list_item_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        return true;
    }
}
  • 1
    Thanks for your answer, but this will only add a spinner on the right on the actionbar... I want the spinner to open when I click on the actionbar title and not an actionbar action – Youb Aug 23 '17 at 21:06