Reputation: 535
I have to create a form in Android which may contain spinner or may not, based on data we have to create spinner. So I am trying to create a dynamic spinner in the form. But it is not working. I am able to create the spinner but when I click on the spinner it show error message.
Code that I wrote:
dynamicSpinner = new Spinner(getApplicationContext());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, option);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
dynamicSpinner.setAdapter(adapter);
option is a ArrayList<String>
, which content the list of the options.
If anyone have solution please share with me.
Upvotes: 0
Views: 2781
Reputation: 2605
try this
Spinner s=new Spinner(yourActivity.this);
ParentLayout.addView(s);
I dont see you adding your spinner to parent layout. I am more interested in what error are you getting exactly
Upvotes: 1
Reputation: 311
Have you tried viewflipper?
http://developer.android.com/reference/android/widget/ViewFlipper.html
Its effective especially for those in need in multiple views/widgets.
The thing is just that, the widgets/views that will be viewed/added is defined in xml.
Hope it helps :D
Upvotes: 0
Reputation: 13390
Have a spinner
in your xml
, then in activity
, use following:
dynamicSpinner = (Spinner)findViewbyID(spinner ID);
if(data available)
populate the spinner;
else
dynamicSpinner.setVisibility(View.Gone);
Hope it helps.
EDIT :
Incase you want to add spinner
progarammatically, still you would be having a layout in xml
which you are using in setContentView(layout id)
.. so get the layout in which all the childs are present in xml
throught its id and then add spinner
to that layout.
Upvotes: 0
Reputation: 9362
Include a spinner in your xml with an id..
and then in code , use:
dynamicSpinner = (Spinner)findViewById(R.id.mydynamicspinner);
instead of
dynamicSpinner = new Spinner(getApplicationContext());
rest all looks fine...
Upvotes: 0