2016-10-04 6 views
0

У меня есть Spinner, у него есть некоторые элементы из parse JSON. JSON отправляет в мое приложение «statusId» и «statusTitle». Как я могу установить свой статус «statusID» JSON в «statusTitle», поэтому на следующем шаге я мог бы позвонить getSelectItem с моим «statusId»?Как назначить идентификатор элемента в spinner?

getSelectItemId неподходящий в этой ситуации, потому что разные «statusId» и «positioId».

P.S. Пожалуйста, не принимайте мой вопрос строго, спасибо.

ответ

0

Сохраните оба из них в разных Arraylist следующим образом.

ArrayList<String> title = new ArrayList<>(); 
    title.add("A"); 
    title.add("B"); 
    title.add("C"); 
    title.add("D"); 

    ArrayList<Integer> id = new ArrayList<>(); 
    id.add(1); 
    id.add(2); 
    id.add(3); 
    id.add(4); 

Теперь название A имеет идентификатор 1, B имеет идентификатор 2 и так далее. Теперь, когда вы выбираете какой-либо элемент. Получите его положение и проверьте предмет в обоих арраистах в этом положении. Вы получите как идентификатор и название

title.get(position of selected item); 
id.get(position of selected item); 
0

Использования класса, чтобы перечислить ваши детали в блеснах:

public class Item { 
    public int id; 
    public String label; 

    @Override 
    public String toString() { return label; } 
} 

добавить в ArrayList или массив пункта к вашему ArrayAdapter и так добавить адаптер к вертушкю ,

Чтобы получить выбранный элемент из блесны:

Item item = (Item) spinner.getSelectedItem(); 

и доступ к идентификатору с item.id

Извините за мой английский.

0

Создать класс с ITEMNAME и ItemId так:

public class EncapTest { 
    private String name; 
    private String idNum; 



    public String getName() { 
     return name; 
    } 

    public String getIdNum() { 
     return idNum; 
    } 


    public void setName(String newName) { 
     name = newName; 
    } 

    public void setIdNum(String newId) { 
     idNum = newId; 
    } 
} 

и заполнить это с помощью пользовательского адаптера.

1

Я создаю класс для сохранения значения ключа, а затем создаю адаптер.

Для заполнения вертушку вы можете сделать что-то подобное:

Spinner keyValueSpinner = (Spinner) rootView.findViewById(R.id.spinner_key_value); 

KeyValueArrayAdapter adapter = new KeyValueArrayAdapter(getActivity(),android.R.layout.simple_spinner_item); 
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
adapter.setEntries(getResources().getStringArray(R.array.statusTitle)); 
adapter.setEntryValues(getResources().getStringArray(R.array.statusId)); 

keyValueSpinner.setAdapter(adapter) 

Обратите внимание, что в этом примере заселить адаптер с массивами внутри в array.xml в ресурсах. Но вы можете заполнить String [], если хотите.

и класс адаптера KeyValueArrayAdaper.java

public class KeyValueArrayAdapter extends ArrayAdapter<KeyValueArrayAdapter.KeyValue> { 

    /** 
    * Key and Value 
    */ 
    public class KeyValue { 
     public String key; 
     public String value; 

     /** 
     * @param key 
     * @param value 
     */ 
     public KeyValue(final String key, final String value) { 
      super(); 
      this.key = key; 
      this.value = value; 
     } 

    } 

    /** 
    * @param context 
    * @param resource 
    * @param textViewResourceId 
    * @param objects 
    */ 
    public KeyValueArrayAdapter(final Context context, final int resource, 
           final int textViewResourceId, 
           final KeyValue[] objects) { 
     super(context, resource, textViewResourceId, objects); 
    } 

    /** 
    * @param context 
    * @param resource 
    * @param textViewResourceId 
    * @param objects 
    */ 
    public KeyValueArrayAdapter(final Context context, final int resource, 
           final int textViewResourceId, 
           final List<KeyValue> objects) { 
     super(context, resource, textViewResourceId, objects); 
    } 

    /** 
    * @param context 
    * @param resource 
    * @param textViewResourceId 
    */ 
    public KeyValueArrayAdapter(final Context context, final int resource, 
           final int textViewResourceId) { 
     super(context, resource, textViewResourceId); 
    } 

    /** 
    * @param context 
    * @param textViewResourceId 
    * @param objects 
    */ 
    public KeyValueArrayAdapter(final Context context, final int textViewResourceId, 
           final KeyValue[] objects) { 
     super(context, textViewResourceId, objects); 
    } 

    /** 
    * @param context 
    * @param textViewResourceId 
    * @param objects 
    */ 
    public KeyValueArrayAdapter(final Context context, final int textViewResourceId, 
           final List<KeyValue> objects) { 
     super(context, textViewResourceId, objects); 
    } 

    /** 
    * @param context 
    * @param textViewResourceId 
    */ 
    public KeyValueArrayAdapter(final Context context, final int textViewResourceId) { 
     super(context, textViewResourceId); 
    } 

    /** 
    * Change the string value of the TextView with the value of the KeyValue. 
    */ 
    @Override 
    public View getView(final int position, final View convertView, final ViewGroup parent) { 
     final TextView view = (TextView) super.getView(position, convertView, parent); 

     view.setText(getItem(position).value); 
     return view; 
    } 

    /** 
    * Change the string value of the TextView with the value of the KeyValue. 
    */ 
    @Override 
    public View getDropDownView(final int position, final View convertView, final ViewGroup parent) { 
     final TextView view = (TextView) super.getDropDownView(position, convertView, parent); 

     view.setText(getItem(position).value); 
     return view; 
    } 

    /** 
    * Set the specified Collection at the array. 
    * 
    * @param keys 
    * @param vaules 
    */ 
    public void setKeyValue(final String[] keys, final String[] vaules) { 
     if (keys.length != vaules.length) { 
      throw new RuntimeException("The length of keys and values is not in agreement."); 
     } 

     final int N = keys.length; 
     for (int i = 0; i < N; i++) { 
      add(new KeyValue(keys[i], vaules[i])); 
     } 
    } 

    /** 
    * Set the specified Collection at the array. 
    * 
    * @param keysVaules 
    */ 
    public void setKeyValue(final String[][] keysVaules) { 
     final int N = keysVaules.length; 
     for (int i = 0; i < N; i++) { 
      add(new KeyValue(keysVaules[i][0], keysVaules[i][1])); 
     } 
    } 

    private String[] entries; 
    private String[] entryValues; 

    /** 
    * Set the specified Collection at the array. 
    * 
    * @param entries 
    */ 
    public void setEntries(final String[] entries) { 
     this.entries = entries; 
     if (entryValues != null) { 
      setKeyValue(entryValues, entries); 
     } 
    } 

    /** 
    * Set the specified Collection at the array. 
    * 
    * @param entryValues 
    */ 
    public void setEntryValues(final String[] entryValues) { 
     this.entryValues = entryValues; 
     if (entries != null) { 
      setKeyValue(entryValues, entries); 
     } 
    } 

    /** 
    * Get the value of the KeyValue with the specified position in the data set. 
    * 
    * @param position 
    * @return 
    */ 
    public String getValue(final int position) { 
     return getItem(position).value; 
    } 

    /** 
    * Get the key of the KeyValue with the specified position in the data set. 
    * 
    * @param position 
    * @return 
    */ 
    public String getKey(final int position) { 
     return getItem(position).key; 
    } 

    /** 
    * Get the entry of the KeyValue with the specified position in the data set. 
    * 
    * @param position 
    * @return 
    */ 
    public String getEntry(final int position) { 
     return getValue(position); 
    } 

    /** 
    * Get the entry value of the KeyValue with the specified position in the data set. 
    * 
    * @param position 
    * @return 
    */ 
    public String getEntryValue(final int position) { 
     return getKey(position); 
    } 

}