Search code examples
androidspinner

Spinner with Key-Value Pair


I am working on multi languages UI. My requirement is in spinner I want to show data in Hindi but when it will be selected it should return english show it can compare to further decision making. Just like tag with tag.

My java code is something like this

    HashMap<String,String> options=new HashMap<String,String>();
    String optionsEnglish [] = getResources().getStringArray(R.array.option_array);
    String optinsHindi[]= getResources().getStringArray(R.array.option_array_hindi);

    for(int i=0;i<optionsEnglish.length;i++)
    {
        options.put(optionsEnglish[i], optinsHindi[i]);
    }
    Spinner optionSpinner = (Spinner) findViewById(R.id.optionPicker);


    ArrayAdapter<HashMap<String, String>> dataAdapter = new ArrayAdapter<HashMap<String,String>>(this, android.R.layout.simple_spinner_item);
    dataAdapter.add(options);


    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    optionSpinner.setAdapter(dataAdapter);

In xml

    <resource>       
            <string-array name="option_array">
                  <item>Market</item>
                  <item>Commodity</item>
            </string-array>

            <string-array name="option_array_hindi">
                  <item>बाजार</item>
                  <item>वस्तु</item>


            </string-array>

     </resources>

Solution

  • Hope this can help you

    Add Data in in Spinner

    private void setDataInSpinner(Spinner id, int dataArray) {
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                    this, dataArray, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
            id.setAdapter(adapter);
        }
    

    To get the selected value of Spinner use this

    Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
    String Text = mySpinner.getSelectedItem().toString();
    

    Or You can use setOnItemSelectedListener to get the selected values

    String value = GetClassCode.getCode(Text);//here u have to pass the value that is selected on the spinner
    

    Create a Class

    public class GetClassCode {
        static HashMap<String, String> codeHash = new HashMap<String, String>();
    
        static {
            init();
        }
    
        public static void init() {
            codeHash.put("key", "value");
            codeHash.put("key", "value");
            codeHash.put("key", "value");
            codeHash.put("key", "value");
    
        }
    
        public static String getCode(String param) {
            return codeHash.get(param);
        }
    }