How to use resource arrays using xml in Android? How to use resource arrays using xml in Android? arrays arrays

How to use resource arrays using xml in Android?


Create an XML like below and put it in res/values/arrays.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <array name="icons">        <item>@drawable/home</item>        <item>@drawable/settings</item>        <item>@drawable/logout</item>    </array>    <array name="colors">        <item>#FFFF0000</item>        <item>#FF00FF00</item>        <item>#FF0000FF</item>    </array></resources>

Then use code like this:

Resources res = getResources();TypedArray icons = res.obtainTypedArray(R.array.icons);Drawable drawable = icons.getDrawable(0);TypedArray colors = res.obtainTypedArray(R.array.colors);int color = colors.getColor(0,0);

Source: http://developer.android.com/guide/topics/resources/more-resources.html


You can use resources from res/values/arrays.xml.

For drawables

<integer-array name="your_images">    <item>@drawable/ic_active_image</item>    <item>@drawable/ic_visited_image</item></integer-array>val position = 1 // Position in array.val drawables = resources.obtainTypedArray(R.array.your_images)val drawable = drawables.getResourceId(position, -1)image.setImageResource(drawable)drawables.recycle()

For colors

<array name="your_colors">    <item>#365374</item>    <item>#00B9FF</item></array>val position = 1val colors = resources.obtainTypedArray(R.array.your_colors)val color = colors.getColor(position, -1)title.setTextColor(color)colors.recycle()

For strings

<string-array name="your_strings">    <item>Active</item>    <item>Visited</item></string-array>val position = 1val strings = resources.getStringArray(R.array.your_strings)title.text = strings[position]

Plurals:

<plurals name="proposal_plurals">    <item quantity="zero">No proposals</item>    <item quantity="one">%1$d proposal</item>    <item quantity="two">%1$d proposals</item>    <item quantity="few">%1$d proposals</item>    <item quantity="many">%1$d proposals</item>    <item quantity="other">%1$d proposals</item></plurals>val count = 117val proposals = count.takeIf { it != 0 }?.let {    resources.getQuantityString(R.plurals.proposal_plurals, it, it)} ?: "No proposals"