Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add items to the spinner dynamically in android?

Tags:

android

how to add items to the spinner dynamically in android?

like image 505
deepthi Avatar asked Jan 29 '10 07:01

deepthi


People also ask

How to populate Spinner in Android dynamically?

add("firstRow"); You don't actually need the getDropDownView, it just helps you if need to customise a little. Well then you have to create a custom adapter, you don't need to write android. R.

How do you populate a spinner?

In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one. To populate the spinner with a list of choices, you then need to specify a SpinnerAdapter in your Activity or Fragment source code.


3 Answers

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?

like image 150
DAS Avatar answered Oct 27 '22 00:10

DAS


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

like image 26
JRL Avatar answered Oct 26 '22 22:10

JRL


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);
like image 25
Md. Al Amin Bhuiyan Avatar answered Oct 26 '22 23:10

Md. Al Amin Bhuiyan