I am working on an android project and I am using a spinner which uses an array adapter which is populated from the database.
I can't find out how I can set the selected item programmatically from the list. For example if, in the spinner I have the following items:
How would I programmatically make Category 2 the selected item when the screen is created. I was thinking it might be similar to c# I.E Spinner.SelectedText = "Category 2" but there doesn't seem to be any method similar to this for Android.
You can make a generic method for this kind of work as I do in my UtilityClass which is
public void SetSpinnerSelection(Spinner spinner,String[] array,String text) {
for(int i=0;i<array.length;i++) {
if(array[i].equals(text)) {
spinner.setSelection(i);
}
}
}
This worked for me:
@Override
protected void onStart() {
super.onStart();
mySpinner.setSelection(position);
}
It's similar to @sberezin's solution but calling setSelection() in onStart().
To find a value and select it:
private void selectValue(Spinner spinner, Object value) {
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).equals(value)) {
spinner.setSelection(i);
break;
}
}
}
If you have a list of contacts the you can go for this:
((Spinner) view.findViewById(R.id.mobile)).setSelection(spinnerContactPersonDesignationAdapter.getPosition(schoolContact.get(i).getCONT_DESIGNATION()));
This is what I use in Kotlin:
spinner.setSelection(resources.getStringArray(R.array.choices).indexOf("Choice 1"))
In my case, this code saved my day:
public static void selectSpinnerItemByValue(Spinner spnr, long value) {
SpinnerAdapter adapter = spnr.getAdapter();
for (int position = 0; position < adapter.getCount(); position++) {
if(adapter.getItemId(position) == value) {
spnr.setSelection(position);
return;
}
}
}
public static void selectSpinnerItemByValue(Spinner spnr, long value) {
SimpleCursorAdapter adapter = (SimpleCursorAdapter) spnr.getAdapter();
for (int position = 0; position < adapter.getCount(); position++) {
if(adapter.getItemId(position) == value) {
spnr.setSelection(position);
return;
}
}
}
You can use the above like:
selectSpinnerItemByValue(spinnerObject, desiredValue);
& of course you can also select by index directly like
spinnerObject.setSelection(index);
I know that is already answered, but simple code to select one item, very simple:
spGenre.setSelection( ( (ArrayAdapter) spGenre.getAdapter()).getPosition(client.getGenre()) );
for (int x = 0; x < spRaca.getAdapter().getCount(); x++) {
if (spRaca.getItemIdAtPosition(x) == reprodutor.getId()) {
spRaca.setSelection(x);
break;
}
}
You can easily set like this: spinner.setSelection(1)
, instead of 1, you can set any position of list you would like to show.
The optimal solution is:
public String[] items= new String[]{"item1","item2","item3"};
// here you can use array or list
ArrayAdapter adapter= new ArrayAdapter(Your_Context, R.layout.support_simple_spinner_dropdown_item, items);
final Spinner itemsSpinner= (Spinner) findViewById(R.id.itemSpinner);
itemsSpinner.setAdapter(adapter);
To get the position of the item automatically add the following statement
itemsSpinner.setSelection(itemsSpinner.getPosition("item2"));
This is stated in comments elsewhere on this page but thought it useful to pull it out into an answer:
When using an adapter, I've found that the spinnerObject.setSelection(INDEX_OF_CATEGORY2)
needs to occur after the setAdapter
call; otherwise, the first item is always the initial selection.
// spinner setup...
spinnerObject.setAdapter(myAdapter);
spinnerObject.setSelection(INDEX_OF_CATEGORY2);
This is confirmed by reviewing the AbsSpinner code for setAdapter
.
Why don't you use your values from the DB and store them on an ArrayList and then just use:
yourSpinner.setSelection(yourArrayList.indexOf("Category 1"));
Some explanation (at least for Fragments - never tried with pure Activity). Hope it helps someone to understand Android better.
Most popular answer by Arun George is correct but don't work in some cases.
The answer by Marco HC uses Runnable wich is a last resort due to additional CPU load.
The answer is - you should simply choose correct place to call to setSelection(), for example it works for me:
@Override
public void onResume() {
super.onResume();
yourSpinner.setSelection(pos);
}
But it won't work in onCreateView(). I suspect that is the reason for the interest to this topic.
The secret is that with Android you can't do anything you want in any method - oops:( - components may just not be ready. As another example - you can't scroll ScrollView neither in onCreateView() nor in onResume() (see the answer here)
Here is the Kotlin extension I am using:
fun Spinner.setItem(list: Array<CharSequence>, value: String) {
val index = list.indexOf(value)
this.post { this.setSelection(index) }
}
Usage:
spinnerPressure.setItem(resources.getTextArray(R.array.array_pressure), pressureUnit)
I have a SimpleCursorAdapter so I have to duplicate the data for use the respose in this post. So, I recommend you try this way:
for (int i = 0; i < spinnerRegion.getAdapter().getCount(); i++) {
if (spinnerRegion.getItemIdAtPosition(i) == Integer
.valueOf(signal.getInt(signal
.getColumnIndexOrThrow("id_region")))) {
spinnerRegion.setSelection(i);
break;
}
}
I think that is a real way
I had made some extension function of Spinner
for loading data and tracking item selection.
Spinner.kt
fun <T> Spinner.load(context: Context, items: List<T>, item: T? = null) {
adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, items).apply {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
if (item != null && items.isNotEmpty()) setSelection(items.indexOf(item))
}
inline fun Spinner.onItemSelected(
crossinline itemSelected: (
parent: AdapterView<*>,
view: View,
position: Int,
id: Long
) -> Unit
) {
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
itemSelected.invoke(parent, view, position, id)
}
}
}
Usaage Example
val list = listOf("String 1", "String 2", "String 3")
val defaultData = "String 2"
// load data to spinner
your_spinner.load(context, list, defaultData)
// load data without default selection, it points to first item
your_spinner.load(context, list)
// for watching item selection
your_spinner.onItemSelected { parent, view, position, id ->
// do on item selection
}
No one of these answers gave me the solution, only worked with this:
mySpinner.post(new Runnable() {
@Override
public void run() {
mySpinner.setSelection(position);
}
});
Most of the time spinner.setSelection(i); //i is 0 to (size-1) of adapter's size
doesn't work. If you just call spinner.setSelection(i);
It depends on your logic.
If view is fully loaded and you want to call it from interface I suggest you to call
spinner.setAdapter(spinner_no_of_hospitals.getAdapter());
spinner.setSelection(i); // i is 0 or within adapter size
Or if you want to change between activity/fragment lifecycle, call like this
spinner.post(new Runnable() {
@Override public void run() {
spinner.setSelection(i);
}
});
This is work for me.
spinner.setSelection(spinner_adapter.getPosition(selected_value)+1);
I had the same issue since yesterday.Unfortunately the first item in the array list is shown by default in spinner widget.A turnaround would be to find the previous selected item with each element in the array list and swap its position with the first element.Here is the code.
OnResume()
{
int before_index = ShowLastSelectedElement();
if (isFound){
Collections.swap(yourArrayList,before_index,0);
}
adapter = new ArrayAdapter<String>(CurrentActivity.this,
android.R.layout.simple_spinner_item, yourArrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item; yourListView.setAdapter(adapter);
}
...
private int ShowLastSelectedElement() {
String strName = "";
int swap_index = 0;
for (int i=0;i<societies.size();i++){
strName = yourArrayList.get(i);
if (strName.trim().toLowerCase().equals(lastselectedelement.trim().toLowerCase())){
swap_index = i;
isFound = true;
}
}
return swap_index;
}
Source: Stackoverflow.com