How to programmatically set spinner entries in android?

I made various string arrays in the string.xml file and I have to set different arrays as entries for the counter according to a specific condition in Java. Is it possible, or is it a database, the only way to do this. Thanks in advance.

+4
source share
3 answers

You need to use the adapter and fill it with an array in the XML file.

Specify the name of your array in xml with the createFromResource method (second parameter).

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.my_array, android.R.layout.simple_spinner_item);   
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
+3
source

You must extract your data from the file:

String[] testArray = getResources().getStringArray(R.array.testArray);

Then you need to inflate the counter:

ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
            this, android.R.layout.simple_spinner_item, testArray );
mySpinner.setAdapter(spinnerArrayAdapter);
+3
source

ArrayAdapter, Spinner.

String data[];
//... do your stuff to get populate this array
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
            this, android.R.layout.simple_spinner_item, data);
mySpinner.setAdapter(spinnerArrayAdapter);

You can also change the presentation of the dropdown elements and customize them further by overriding this class.

+1
source

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


All Articles