Hend
Hend

Reputation: 599

Mapping value selected in Spinner to other values

I got a spinner of items, e.g. {Apples, Oranges, Eggs, Bread}. When user selects "Eggs" it's value/cost ($2) would be used in a computation of total cost later. How can I map a value(cost of item) with the item selected by the user in the spinner? I'm a little confused whether it's possible. It seems like it is having 2 values.

Something like:

double totalExpenses = $23 + (cost of the item user selected)

strings.xml

<string-array name="spinner_array">
<item>Apples</item>
<item>Oranges</item>
<item>Eggs</item>
<item>Bread</item>
</string-array>

Upvotes: 2

Views: 1451

Answers (2)

Sarwar Erfan
Sarwar Erfan

Reputation: 18068

If you want to avoid creating your own adapter (sometimes you want this to keep it simple)

Have another array of same size, which has the prices:

<string-array name="spinner_array">
   <item>Apples</item>
   <item>Oranges</item>
   <item>Eggs</item>
   <item>Bread</item>
</string-array>

<string-array name="spinner_array_values">
   <item>5.99</item>
   <item>6.99</item>
   <item>2.99</item>
   <item>12.99</item>
</string-array>

Then, on your event handler, get the selected index of the spinner. Use that index to get the price from the second array.

double totalExpenses = $23 + Double.parseDouble(value of spinner_array_values index at the spinner selected index);

=== EDIT (code sample) ====

int selectedIndex = spinner.getSelectedItemPosition();
String[] price_array = getResources().getStringArray(R.array.spinner_array_values);
double totalExpenses = 23 + Double.parseDouble(price_array[selectedIndex]);

OR

double totalExpenses = 23 + Double.parseDouble(getResources().getStringArray(R.array.spinner_array_values)[spinner.getSelectedItemPosition()]);

Upvotes: 2

Knossos
Knossos

Reputation: 16048

Personally, I would create a custom ArrayAdapter. That would let you use your own class (class Food, for example) as the item in the list.

That way you can do all of your calculations abstracted.

This video may get you started on the right foot.

Upvotes: 0

Related Questions