How to add an item to Spinner Android

How to add an element from str to spinner? I tried with ArrayList, ArrayAdapter, but did not work ...

String[] str={"item 1","item 2","item 3"}; Spinner s=(Spinner)findViewById(R.id.spinner); 
+6
source share
3 answers

You can use a simple default ArrayAdapter array to achieve your requirement dynamically. Below is a snippet of code that you can execute and modify your onCreate method to add values ​​to the counter.

  spinner = (Spinner) findViewById(R.id.spinner); ArrayAdapter<String> adapter; List<String> list; list = new ArrayList<String>(); list.add("Item 1"); list.add("Item 2"); list.add("Item 3"); list.add("Item 4"); list.add("Item 5"); adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); 

if you want the counter values ​​to be added statically, you can add an array to the xml file and assign the entries attribute to the counter. Below is a snippet of code.

Your xml file layout

 <Spinner android:id="@+id/spinner" android:layout_width="fill_parent" android:drawSelectorOnTop="true" android:prompt="@string/spin" android:entries="@array/items" /> 

In arrays.xml file

 <string-array name="items"> <item>Item 1</item> <item>Item 2</item> <item>Item 3</item> <item>Item 4</item> <item>Item 5</item> </string-array> 
+18
source

The Android link has a good example and instead of using:

 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.planets_array, android.R.layout.simple_spinner_item); 

as indicated in the example (this is due to the fact that Spinner populated from an existing string array resource defined in the xml file), you can use the ArrayAdapter constructor, which takes List as its argument, as shown at:

http://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter%28android.content.Context,%20int,%20java.util.List%3CT%3E%29

You can do it like this:

 ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.your_layout,mYourList) 

where mYourList can be an ArrayList<String> , where you can store the data that Spinner wants to fill.

+2
source
+1
source

Source: https://habr.com/ru/post/972452/


All Articles