What's the correct way to implement key-value pair in Spinner in android

后端 未结 4 1710
無奈伤痛
無奈伤痛 2020-12-04 14:15

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         


        
相关标签:
4条回答
  • 2020-12-04 14:52

    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...

    0 讨论(0)
  • 2020-12-04 14:57

    Create a map of key-values, and take a value in onItemSelected(you can obtain "key" via spinner.getAdapter().getItem(position)).

    0 讨论(0)
  • 2020-12-04 15:02

    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() );
    }
    
    0 讨论(0)
  • 2020-12-04 15:09

    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);
    
    0 讨论(0)
提交回复
热议问题