and_azlan and_azlan - 3 months ago 21
Android Question

How to add Spinner on NavigationView

How to add Spinner on NavigationView list? Is it possible?

enter image description here

Answer

Yes, now its possible with android support version 23.1+, See this official blogpost.

1.First create a xml layout spinner_menu.xml with a spinner item

<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_gravity="center_vertical"
    android:gravity="center_vertical"
    android:layout_height="match_parent">
</Spinner>

2.Than link it to the navigation view menu xml like this

<item android:id="@+id/nav_lang"
     android:icon="@android:drawable/ic_menu_manage"
     android:title="Language"
     app:actionLayout="@layout/spinner_menu"/>

3.If you want to access it in your activity, like add action when spinner item is selected,

Spinner sp = (Spinner) navigationView.getMenu().findItem(R.id. nav_lang).getActionView();
    sp.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,langs));
    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(MainActivity.this,langs[position],Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

Where langs is a string array or array list to display items in spinner.

It will look something like below,

enter image description here

Hope it will help you buddy!.