V. Raman
V. Raman

Reputation: 221

Android / Changing the text in specific spinner item

I am designing a mobile app for jewellery shop. In Android, for the jewellery product description page, I have a Spinner with some ring sizes with their text 5 to 25 set by using a custom array list adapter.

I have a Radio Group of 18 carat or 22 carat that work along with the Spinner, and if different Radio Button for carat is selected, then the spinner text should change along with it only for a few ring sizes, for example 17 - Ships in 24 hours if the ring size is ready to ship and 18 if the ring size is to be newly made based upon customer's order.

To achieve this, if a different size Radio Button is selected, I create a new array list, add all the new text again for spinner and then use array adapter again.

ArrayAdapter adapter = new ArrayAdapter(Description.this, android.R.layout.simple_spinner_item, sizes);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);

In doing so, the Spinner automatically defaults to the first item 5 always, even if previously the spinner item selected was, for example, 17 size for a different carat Radio Button.

And also, the other details corresponding to other Text Views in the same activity, for example price, discount, making charge, gold weight, delivery date, whether product is ready to ship, etc. automatically default to the ring size 5.

So, is it possible to change the text of a specific Spinner item programmatically if a different carat Radio Button is selected? Is it possible to achieve that without creating a new array list, add all the new text to it and making use of array adapter again? And if so how?

Upvotes: 1

Views: 901

Answers (2)

Akhil Soman
Akhil Soman

Reputation: 2217

If sizes is an ArrayList, to change a particular item in the spinner try using

sizes.set(index,newItem)

If you want to change the 3rd item to 10,

sizes.set(2,10) //I am assuming the sizes arraylist is integer arraylist. if not change to required data type

then execute

adapter.notifyDataSetChanged() // This will refresh you spinner.

instead of re-setting the adapter on the spinner. And then if you want, execute

s1.setSelection(2)

The s1.setAdapter(adapter); should only be executed once(when the spinner is initialised).

public void refreshSpinner(int index,int newValue){ 
    sizes.set(index,newValue);
    adapter.notifyDataSetChanged();

    //Only if you want to select the new value
    s1.setSelection(index);
}

Upvotes: 2

Sajith
Sajith

Reputation: 771

Try below code,

Select the Spinner element at index position 2 (It will select third element/item from Spinner)

s1.setSelection(2);

Upvotes: 1

Related Questions