views:

1494

answers:

2

Hi,

In the user interface there has to be a spinner which contains some names (the names are visible) and each name has its own ID (the IDs are not equal to display sequence). When the user selects the name from the list the variable currentID has to be changed.

The application contains the ArrayList

Where User is an object with ID and name:

public class User{
        public int ID;
        public String name;
    }

What I don't know is how to create a spinner which displays the list of user's names and bind spinner items to IDs so when the spinner item is selected/changed the variable currentID is set to appropriate value.

I would appreciate if anyone could show the solution of the described problem or provide any link useful to solve the problem.

Thanks!

+1  A: 

Niko - you can look at this answer. You can also go with custom adapter but the solution below is fine for simple cases Here's re-post:

So if you came here because you want to have both label and value in the Spinner - here's how I did it:

  1. Just create your Spinner the usual way
  2. Define 2 equal size arrays in your array.xml file. One for labels, one for values
  3. Set your Spinner with android:entries="@array/labels" 4.

    In your code - when you need a value do something like this (no you don't have to chain it):

    String selectedVal = getResources().getStringArray(R.array.values)[spinner .getSelectedItemPosition()];

DroidIn.net
A: 

Works fine for me, the code needed around the getResource() thing is as follows:

spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> spinner, View v,
                int arg2, long arg3) {
            String selectedVal = getResources().getStringArray(R.array.compass_rate_values)[spinner.getSelectedItemPosition()];
            //Do something with the value
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }

    });

Just need to make sure (by yourself) the values in the two arrays are aligned properly!

Sonja