Issue
Does anyone here know how can i store the retrieved drawables using java.lang.reflect.Field to a int[] lips = new int[] {}, so that i can use it in my listview.
java.lang.reflect.Field[] drawables = R.drawable.class.getFields();
lips = new int[20];
for (java.lang.reflect.Field f : drawables) {
try {
if(f.getName().contains("l_1_")){
System.out.println("R.drawable." + f.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
OUTPUT:
10-25 09:35:20.748: I/System.out(14461): R.drawable.l_1_1
10-25 09:35:20.748: I/System.out(14461): R.drawable.l_1_2
10-25 09:35:20.748: I/System.out(14461): R.drawable.l_1_3
10-25 09:35:20.748: I/System.out(14461): R.drawable.l_1_4
Solution
You should use getDeclaredFields() rather than getFields and also you should use the drawableResources as
final Field[] fields = R.drawable.class.getDeclaredFields();
final R.drawable drawableResources = new R.drawable();
List<Integer> lipsList = new ArrayList<>();
int resId;
for (int i = 0; i < fields.length; i++) {
try {
if (fields[i].getName().contains("l_1_")){
resId = fields[i].getInt(drawableResources);
lipsList.add(resId);
}
} catch (Exception e) {
continue;
}
}
Taken from here
The better approach is store resources related to the list in the integer-array
in your arrays.xml
or strings.xml
file like below
<integer-array name="images_for_my_list">
<item>@drawable/abc_menu_hardkey_panel_mtrl_mult</item>
<item>@drawable/mylist_img_2</item>
<item>@drawable/abc_menu_hardkey_panel_mtrl_mult</item>
<item>@drawable/mylist_img_3</item>
</integer-array>
And use it as
TypedArray tArray = mcontext.getResources().obtainTypedArray(
R.array.images_for_list);
int count = tArray.length();
int[] ids = new int[count];
for (int i = 0; i < ids.length; i++) {
ids[i] = tArray.getResourceId(i, 0);
// How to Use it
// setImageResource(ids[position]);
// Or
// Drawable drawable = ContextCompat.getDrawable(mContext.getApplicationContext(),ids[position])
// imageView.setImageDrawable(drawable);
}
Answered By - ProblemSlover
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.