How to access a string using a dynamic string name in android (similar to eval in javascript)?

Standard

You have to use “android.content.res.Resources.getIdentifier”.

Strings:
strCategory1
strCategory2
strCategory3

for (int i=0; i<n; i++){
 int resID = getResources().getIdentifier("strCategory" + position, "string", getPackageName());
 String strTest = getResources().getString(resID);
}

String Arrays:
strArray1
strArray2
strArray3

for (int i=0; i<n; i++){
 int resID = getResources().getIdentifier("strArray" + position, "array", getPackageName());
 String[] strArrayTest = getResources().getStringArray(resID);
}

Drawables:
ic_category1
ic_category2
ic_category3

for (int i=0; i<n; i++){
 int resID = getResources().getIdentifier("ic_category" + position, "drawable", getPackageName());
 imgIcon.setImageDrawable(getResources().getDrawable(resID));
}

Leave a Reply

Your email address will not be published. Required fields are marked *