How to set the value and text in a Spinner from a

2020-08-09 04:43发布

问题:

i am working on android spinner control. i already have populate list of string to show in spinner like

String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
        SpinnerName.setAdapter(adapter);

this is working well but i need to add unique id for my list like

  1. Office = 4

  2. Home = 8

  3. College = 9

  4. Uncle's Home = 10

  5. CoDebiggers = 55

    how can i set there value with String list? and how can i get these values by selected item change?

回答1:

You have to create two array, one for the items and second for the item's value.

String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
int[] items_value = new String[]{ 4, 8, 9, 10, 55};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
SpinnerName.setAdapter(adapter);

Get spinner selected item respective value from value array:

int value = items_value[SpinnerName.getSelectedItemPosition()];



回答2:

Create another array, maintain sizes of both arrays same. One is for items and another one is for itemIds. inside OnclickLisener of spinner call itemsId array like below.

String[] itemsId = new String[]{ "4", "8", "9", "10","55"};
String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
    SpinnerName.setAdapter(adapter);
SpinnerName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

           String id = itemsId.get(i);
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });