Issue
I have a resource file like this:
strings.xml
<string name="category01">My Category 01</string>
<string name="category02">My Category 02</string>
<string name="category03">My Category 03</string>
<string-array name="array_category_01">
<item name="title">@string/category01</item>
<item name="image">@drawable/img01</item>
</string-array>
<string-array name="array_category_02">
<item name="title">@string/category02</item>
<item name="image">@drawable/img02</item>
</string-array>
<string-array name="array_category_03">
<item name="title">@string/category03</item>
<item name="image">@drawable/img03</item>
</string-array>
<string-array name="categories_array">
<item>@array/array_category_01</item>
<item>@array/array_category_02</item>
<item>@array/array_category_03</item>
</string-array>
Note: @drawable/img01, @drawable/img02 and @drawable/img03 are png images locates at res\drawable folder
Later I perform below iteration to retrieve category-images pairs:
Resources res = this.context.getResources();
TypedArray ta = res.obtainTypedArray(R.array.categories_array);
int n = ta.length();
String[][] array = new String[n][];
for (int i = 0; i < n; ++i) {
int id = ta.getResourceId(i, 0);
if (id > 0) {
array[i] = res.getStringArray(id);
} else {
// something wrong with the XML
}
}
ta.recycle();
so for example at the end I get an array which contents are:
array[0]
|
---> [0] "My Category 01"
|
---> [1] "res/drawable-xxhdpi-v4/img01.png"
array[1]
|
---> [0] "My Category 02"
|
---> [1] "res/drawable-xxhdpi-v4/img02.png"
array[2]
|
---> [0] "My Category 03"
|
---> [1] "res/drawable-xxhdpi-v4/img03.png"
It is just what I am expected to get, no problem until here.
Later in my code, I need to get the resource ID of one of the categories contained in the above array in order for set the content of an ImageView object so I perform below (let's say I want the image for category 2):
ImageView imageView = (ImageView) rowView.findViewById(R.id.categoryicon);
int resID = this.context.getResources().getIdentifier(array[1][1] , "drawable", this.context.getPackageName());
imageView.setImageResource(resID);
My problem is that resID is zero so it means drawable resource has not been found...
In order to work I need image names in the array to be img01, img02, img03 instead of "res/drawable-xxhdpi-v4/img01.png", "res/drawable-xxhdpi-v4/img02.png" and "res/drawable-xxhdpi-v4/img03.png" respectively so when I pass the names to getIdentifier through array[x][y] it works.
How can I get rid of this?
Solution
One simple solution would be to parse the string and get only the image name as below.
String[] Image1 = array[1][1].split("/");
String s = Image1[Image1.length-1].replace(".png","").trim();
int resID = this.context.getResources().getIdentifier(s , "drawable", this.context.getPackageName());
Answered By - Prem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.