sir-haver :
I know the question was already asked here: How to add a Dropdown item on the action bar
I'm trying to implement the solutions but can't figure out the Kotlin code to make it work. I'm sorry, I'm still new to Android development.
I created the overflow_menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item android:id="@+id/spinner"
android:title="haveri"
yourapp:showAsAction="ifRoom"
yourapp:actionViewClass="android.widget.Spinner" />
</menu>
Then I'm trying to translate this code to Kotlin:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
MenuItem item = menu.findItem(R.id.spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(item); // get the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(onItemSelectedListener);
I tried the following:
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
getMenuInflater().inflate(R.menu.overflow_menu, menu)
val item = menu?.findItem(R.id.spinner)
val spinner = MenuItemCompat.getActionView(item) as (Spinner) // get the spinner
spinner.adapter = adapter
spinner.setOnItemSelectedListener(onItemSelectedListener);
}
But I don't understand what is the adapter here? Could someone please point me to the relevant documentation? Thank you very much
Simon Pham :
You can create a simple adapter to use with spinner:
ArrayAdapter.createFromResource(
this,
R.array.planets_array,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
spinner.adapter = adapter
}
Add this to res/values/arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
I took that code from the example in this official documentation:
Spinner: https://developer.android.com/guide/topics/ui/controls/spinner