Is this the correct way to implement key-value pair for a Spinner in Android?
package com.mypackage
import android.app.Activity;
import android.os.Bundle;
i
this is one way. i use it quite a lot though i use my own adapter (inheriting from BaseAdpater). Another way would b like the above to have an index (0,1,2 etc ) mappd to a value and when you get an item get it's index a well so you can retrieve it's value fro mthe map. I like that option less...
Create a map of key-values, and take a value in onItemSelected(you can obtain "key" via spinner.getAdapter().getItem(position)).
To avoid reaching back into items[]
from the listener use getItemAtPosition
which returns an Object from the Adapter. To access the MyData
methods you must cast the object like so:
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
MyData d = (MyData) parent.getItemAtPosition(position);
valueTextView.setText( d.getValue() );
}
I created an HashMap adapter for use in these scenarios. Also see example project here
mapData = new LinkedHashMap<String, String>();
mapData.put("shamu", "Nexus 6");
mapData.put("fugu", "Nexus Player");
mapData.put("volantisg", "Nexus 9 (LTE)");
mapData.put("volantis", "Nexus 9 (Wi-Fi)");
mapData.put("hammerhead", "Nexus 5 (GSM/LTE)");
mapData.put("razor", "Nexus 7 [2013] (Wi-Fi)");
mapData.put("razorg", "Nexus 7 [2013] (Mobile)");
mapData.put("mantaray", "Nexus 10");
mapData.put("occam", "Nexus 4");
mapData.put("nakasi", "Nexus 7 (Wi-Fi)");
mapData.put("nakasig", "Nexus 7 (Mobile)");
mapData.put("tungsten", "Nexus Q");
adapter = new LinkedHashMapAdapter<String, String>(this, android.R.layout.simple_spinner_item, mapData);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);