Spinner cannot load an integer array?

后端 未结 2 1255
慢半拍i
慢半拍i 2021-01-11 13:16

I have an application, which has a Spinner that I want populated with some numbers (4,8,12,16). I created an integer-array object in strings.xml with the items mentioned ab

相关标签:
2条回答
  • 2021-01-11 13:44

    To overcome this problem, simply put quotes around your int values

    <array name="spinner_value">
        <item>"18"</item>
        <item>"8"</item>
    </array>
    
    0 讨论(0)
  • 2021-01-11 14:05

    What you are attempting to do is not supported.

    You likely have some code that looks like this:

    ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
        R.array.numbers, android.R.layout.simple_spinner_item);
    

    Which is of course calling the following:

    /**
     * Creates a new ArrayAdapter from external resources. The content of the array
     * is obtained through {@link android.content.res.Resources#getTextArray(int)}.
     *
     * @param context The application's environment.
     * @param textArrayResId The identifier of the array to use as the data source.
     * @param textViewResId The identifier of the layout used to create views.
     *
     * @return An ArrayAdapter<CharSequence>.
     */
    public static ArrayAdapter<CharSequence> createFromResource(Context context,
            int textArrayResId, int textViewResId) {
        CharSequence[] strings = context.getResources().getTextArray(textArrayResId);
        return new ArrayAdapter<CharSequence>(context, textViewResId, strings);
    }
    

    The call to getTextArray returns an array with null objects rather than the string representation of the values in your integer array. Digging deeper reveals the source of the problem is in a method of AssetManager:

    /**
     * Retrieve the text array associated with a particular resource
     * identifier.
     * @param id Resource id of the string array
     */
    /*package*/ final CharSequence[] getResourceTextArray(final int id) {
        int[] rawInfoArray = getArrayStringInfo(id);
        int rawInfoArrayLen = rawInfoArray.length;
        final int infoArrayLen = rawInfoArrayLen / 2;
        int block;
        int index;
        CharSequence[] retArray = new CharSequence[infoArrayLen];
        for (int i = 0, j = 0; i < rawInfoArrayLen; i = i + 2, j++) {
            block = rawInfoArray[i];
            index = rawInfoArray[i + 1];
            retArray[j] = index >= 0 ? mStringBlocks[block].get(index) : null;
        }
        return retArray;
    }
    

    This code assumes you have provided the resource id of an array of strings and thus it is unable to properly extract out values from your array of integers.

    0 讨论(0)
提交回复
热议问题