Android Adding Spinner To ActionBar

The app bar, also known as the action bar, is one of the most important design elements in your app's activities, it allows users to quickly understand how to operate your app and have a great experience .

Android Spinner Widget Provides a quick way to select one value from a set , Touching the spinner displays all available value from which user can select one .

In this tutorial we will see adding spinner widget to ActionBar thru option menu 




1. Menu


Inside menu for item tag set the actionViewClass property with AppCompatSpinner class and set showAsAction property with always(Always show this item in an actionbar) .

file : main_menu.xml
<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="@string/action_spinner"
        app:actionViewClass="androidx.appcompat.widget.AppCompatSpinner"
        app:showAsAction="always" />
</menu>


2. XML Layout


Just an empty layout for MainActivity

file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"/>


XML Layout for drop down XML layout for spinner items which will be set to adapter

file : layout_drop_title . 
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?attr/spinnerDropDownItemStyle"
    android:singleLine="true"
    android:layout_width="wrap_content"
    android:layout_height="?attr/actionBarSize"
    android:textColor="@android:color/white"
    android:ellipsize="marquee"/>

XML Layout for Spinner Checked Item this layout set by calling setDropDownViewResource on adapter reference . 

file : layout_drop_list . 
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/spinnerDropDownItemStyle"
    android:singleLine="true"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:ellipsize="marquee"
    android:background="@color/colorPrimary"
    android:textColor="@android:color/white"/>


3. MainActivity


  1. Inside onCreate function set the above defined XML Layout 
  2. Override the onCreateOptionsMenu fun of Activity and set the above defined xml layout using menuInflater .
  3. Get the reference of menu item and call getView and then type cast it AppCompatSpinner.
  4. Create an ArrayAdapter and set it to spinner .
  5. Set the onItemSelectedListener for spinner widget , when uses selects the items perform the action .  


file : MainActivity.kt
package com.tutorialsbuzz.toolbarspinner

import android.os.Bundle
import android.view.Menu
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatSpinner
import java.util.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)

        val item = menu?.findItem(R.id.spinner)
        val spinner = item?.actionView as AppCompatSpinner

        var arrayAdapter =
            ArrayAdapter(this@MainActivity, R.layout.layout_drop_title, getCountries())
        arrayAdapter.setDropDownViewResource(R.layout.layout_drop_list)
        spinner.adapter = arrayAdapter

        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

            override fun onItemSelected(p0: AdapterView<*>?, view: View?, position: Int, id: Long) {
                showToast(getCountries()[position] + " selected")
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {}
        }
        return true
    }

    private fun getCountries(): MutableList<String> {
        val mdList = mutableListOf<String>()
        for (countryISO in Locale.getISOCountries()) {
            val locale = Locale("", countryISO)
            if (!locale.displayCountry.isEmpty()) {
                mdList.add(locale.displayCountry + "  " + counrtyFlag(countryISO))
            }
        }
        return mdList
    }

    private fun counrtyFlag(countryCode: String): String {
        val flagOffset = 0x1F1E6
        val asciiOffset = 0x41
        val firstChar = Character.codePointAt(countryCode, 0) - asciiOffset + flagOffset
        val secondChar = Character.codePointAt(countryCode, 1) - asciiOffset + flagOffset
        return (String(Character.toChars(firstChar)) + String(Character.toChars(secondChar)))
    }

    private fun showToast(msg: String) {
        Toast.makeText(
            this@MainActivity, msg, Toast.LENGTH_SHORT
        ).show()
    }
}





No comments:

Post a comment