Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spinner adding string array on item selection how can get item related value in android

i am developing one spinner this spinner i am string array

spinner = (Spinner)this.findViewById(R.id.mlg); 
final CharSequence[] itemArray =getResources().getTextArray(R.array.RectBeam); 
final List<CharSequence> itemList =new ArrayList<CharSequence>(Arrays.asList(itemArray)); 
adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,itemList); 

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 

spinner.setAdapter(adapter); 
spinner.setOnItemSelectedListener(new OnItemSelectedListener() { 

public void onItemSelected(AdapterView<?> parent, View view, 
int pos, long id) { 
Toast.makeText(parent.getContext(), "The planet is " + 
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show(); 

} 

............................

<string-array name="RectBeam">
<item value="3000000" > Steel</item></string-array> 

this is the spinner related string array i am get the spinner item i am using parent.getItemAtPosition(pos).toString(),done my problem is particular item value how can get

example :  steel----------->3000000 
like image 279
Narasimha Avatar asked Mar 09 '11 10:03

Narasimha


1 Answers

I am not sure either Spinner allow that attribute value in XML String or not but your problem can be solved like this.

Create two arrays in your array.xml file like:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="items">
        <item>Nokia 1200</item>
        <item>Nokia 1600</item>
        <item>Nokia 5130</item>
    </string-array>
    <string-array name="values">
        <item>1000</item>
        <item>2000</item>
        <item>5000</item>
    </string-array>
</resources>

Now load first array in your adapter and store the second one in other Array to hold values of items as:

String items [] = getResources().getStringArray(R.array.items);
String values [] =  getResources().getStringArray(R.array.values);

And you can simply get the respective item name and value in your onItemSelected() method like this:

String item = parent.getItemAtPosition(pos).toString();
String value = values [pos];
like image 99
Vikas Patidar Avatar answered Oct 23 '22 23:10

Vikas Patidar