问题
I have created my application by populating spinners within my Java code. I am now trying to convert it to populating my Spinners from my strings.xml file. I have followed a few websites( example 1 and example 2 ), but have not been able to get my code to work.
The main problem with those is that the ArrayAdapter's they use are of type <CharSequence>
. Can I do this somehow using <String>
ArrayAdapters?
This is my array in my XML file :
<string-array name="anti_pump_ap_mode_array">
<item>OFF</item>
<item>Anti-Pump</item>
<item>Motor Cut...</item>
</string-array>
Here is the code I've tried :
apModeAdapter = new ArrayAdapter<String>(this, R.array.anti_pump_ap_mode_array, android.R.layout.simple_spinner_item );
apModeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, R.array.anti_pump_ap_mode_array );
apModeAdapter = ArrayAdapter.createFromResource(this, android.R.layout.simple_spinner_item, R.array.anti_pump_ap_mode_array );
Of course the last one gives me an error, but the first two just do not populate my spinner. When I run the application the Spinner is just empty.
回答1:
Use below way, interchange array id and layout id. Textarray resource id is second parameter
apModeAdapter = ArrayAdapter.createFromResource(this, R.array.anti_pump_ap_mode_array, android.R.layout.simple_spinner_item, );
Edit: For the first way to work. get the string array from resources
Resources res = getResources();
apModeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, res.getStringArray(R.array.anti_pump_ap_mode_array) );
回答2:
CharSequence
is an interface that String
implements, so even though the API createFromResource()
returns the interface type, it is still filled with your String
array. If you truly needed to access the results as a String later, you could cast the accessor. However, most Android UI methods take CharSequence
as input also.
In addition, the parameters are reversed. It should look like this:
ArrayAdapter.createFromResource(this, R.array.anti_pump_ap_mode_array, android.R.layout.simple_spinner_item );
来源:https://stackoverflow.com/questions/12109718/populate-spinner-from-string-array-source-with-a-string-arrayadapter