开发者

so how to add a int array to a spinner in android

开发者 https://www.devze.com 2023-04-06 01:03 出处:网络
so I have a int array and a spinner, I need the spinner to show the values of the int array. Being a novice, I am not sure how to add an int array to an arrayadapter or simpleadapter. I can use a list

so I have a int array and a spinner, I need the spinner to show the values of the int array. Being a novice, I am not sure how to add an int array to an arrayadapter or simpleadapter. I can use a list as well instead on an array, but it will always contain integer values.

mspin=(Spinner) findViewById(R.id.spinner1);
int[] items=new int[]{1,2,3,4};
ArrayAdapter<int[]> ad=new ArrayAdapter(this,android.R.layout.simple_spinner_item);

//ad.add(items); // this cause 开发者_JAVA技巧some value to be displayed, possible the id of the item.

mspin.setAdapter(ad);

Thank you


You have to use Integer, not int. This syntax works:

Integer[] items = new Integer[]{1,2,3,4};
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_spinner_item, items);


Doesn't that just work? Since the default ArrayAdapter implementation simply calls .toString() on each item. Perhaps you need to use an Integer instead (which is an object). Alternatively, you could implement your own custom adapter extending ArrayAdapter or moving to an array of strings to begin with.


If you are getting values from resources arrays then you should add double quotations around your integer items like this:

<array name="values">
    <item>"1"</item>
    <item>"2"</item>
    <item>"3"</item>
    <item>"4"</item>
    <item>"5"</item>
</array>

Then simply get values as a String array from resources and set them into adapter.

String[] values = getResources().getStringArray(R.array.values);
ArrayAdapter<String> ad = new ArrayAdapter(this, android.R.layout.simple_spinner_item, values);
mspin.setAdapter(ad);
0

精彩评论

暂无评论...
验证码 换一张
取 消