23

how to add items to the spinner dynamically in android?

deepthi
  • 8,477
  • 12
  • 35
  • 36

3 Answers3

34
Spinner spinner = (Spinner)findViewById(R.id.mySpinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, android.R.id.text1);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinnerAdapter.add("value");
spinnerAdapter.notifyDataSetChanged();

the above is in case of the array adapter, I believe you know how to populate values with ArrayAdapter .

How can we do this in case of the SimpleCursorAdapter, i.e if we have 2 spinners and if we select the values of one spinner (that is getting the value from SimpleCursorAdapter) depending on some criteria the other spinner should be filled with values. how can we achieve that?

DAS
  • 686
  • 8
  • 13
  • i had the same question, i followed your answer, it works, but text is white at the spinner initial value. Any hints? – thahgr Sep 16 '19 at 13:20
  • 1
    I used the example at this post and it worked: https://android--code.blogspot.com/2015/08/android-spinner-add-item-dynamically.html – DeSpeaker Jan 04 '20 at 18:09
8

By calling ArrayAdapter.add to the Spinner's ArrayAdapter.

JRL
  • 76,767
  • 18
  • 98
  • 146
1

You can follow this way

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);

you can also select by index directly like

spinnerObject.setSelection(index);
Md. Al Amin Bhuiyan
  • 303
  • 1
  • 3
  • 12