1

I have created a TextView in android like the code below:

txtv = new TextView(this);
txtv.setText("text");
ll.addView(txtv); 

Same way I have created a spinner:

spinner = new Spinner(this);
ll.addView(spinner);

But I am unable to populate value on the spinner. Most tutorials giving populating spinner with ArrayAdapter but it is taking id of xml, like R.id..... Since I am creating dynamic, I can't do like that way. How can I populate spinner dynamically?

The Heist
  • 1,444
  • 1
  • 16
  • 32
androidGenX
  • 1,108
  • 3
  • 18
  • 44

3 Answers3

2

Add in bellow way

ArrayList<String> list = new ArrayListString();
 list.add("First");
 list.add("Second");
 ArrayAdapter adapter= new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list); 
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
    spinner.setAdapter(adapter);
Srikanth
  • 584
  • 1
  • 6
  • 21
0

You need to get layout

View linearLayout =  findViewById(R.id.layoutID);
Cerate spinner

   Spinner spinner = new Spinner(this);
//Make sure you have valid layout parameters.
spinner .setLayoutParams(new     LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

                ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
                        android.R.layout.simple_spinner_dropdown_item, spinnerList);
                spinner.setAdapter(spinnerArrayAdapter);
Then add spinner to view

((LinearLayout) linearLayout).addView(spinner );
Pankaj Arora
  • 10,224
  • 2
  • 37
  • 59
0

You don't put a textview in a spinner. Spinner already has a CheckedTextView inside the rows. Here's an example you can use.

yourAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item){
            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
CheckedTextView view = (CheckedTextView) super.getDropDownView(position, convertView, parent);
                return view;
            }
        };

yourSpinner.setAdapter(yourAdapter);

You simply add a String to your adapter by using

yourAdapter.add("firstRow");

You don't actually need the getDropDownView, it just helps you if need to customise a little.

Barışcan Kayaoğlu
  • 1,294
  • 3
  • 14
  • 35
  • 1
    I don't have android.R.layout.simple_spinner_item . Because it is dynamic layout. I have LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); sv.addView(ll); – androidGenX Mar 19 '14 at 03:35
  • 1
    Well then you have to create a custom adapter, you don't need to write android.R.layout.simple_spinner_item as your layout, you can create a row layout and set it, then you can set the contents in getView(). – Barışcan Kayaoğlu Mar 19 '14 at 09:53
  • You can skip that parameter, android.R.layout.simple_spinner_item is the visual look of the control, if you skip it the control will look like your current style – Windgate Jun 18 '21 at 09:46