Java – Android: How do I add enumeration tags to the spinner, instead of enum.values()?

Android: How do I add enumeration tags to the spinner, instead of enum.values()?… here is a solution to the problem.

Android: How do I add enumeration tags to the spinner, instead of enum.values()?

I’m trying to make a fine-tuned list where my users can select language translations based on the enumeration “language” class.

Adding “Language.values()” works,
BUT THE SPINNER SHOWS “AF” INSTEAD OF “AFRIKAANS”
I want the name “AFRIKAANS” to be displayed in the spinner, onItemSelected I want to get the “af” value.

Is this possible?

public enum Language {
       AUTO_DETECT(""),
       AFRIKAANS("af"),
       ALBANIAN("sq"),
       AMHARIC("am") .... and so no..

Check out the hold enumeration class here:
http://code.google.com/p/google-api-translate-java/source/browse/trunk/src/com/google/api/translate/Language.java

spinnerLanguage = (Spinner) findViewById(R.id.translate_spinner_language);
spinnerLanguage.setAdapter(new ArrayAdapter<Language>(this, android. R.layout.simple_spinner_item, Language.values()));
spinnerLanguage.setOnItemSelectedListener(new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) 
    {
       Log.i("language", parent.getItemAtPosition(pos).toString());
    }
    public void onNothingSelected(AdapterView<?> parent) 
    {
    }
});

Solution

Instead of overriding toString(), change it to a different function:

public String shortCode() {
  return language;
}

This way, toString() will return AFRIKAANS for the Spinner display, and you can call shortCode() to get af in onItemSelected().

Related Problems and Solutions