Refer to id of views dynamically with template strings? - android

(I'm sorry if I didn't use the correct term in the title.)
I have many widgets of ImageView with ids of image1, image2, image3, etc.
I would like to refer to one of them (for example image2) dynamically using an integer, something like:
val position = 2
image{position}.x = ....
Is such thing possible in Kotlin/Android? I'm only trying this direction since I know it's possible in JavaScript

You can use getIdentifier to get the identifier of your images like so:
int resId = context.resources.getIdentifier(
"image${position}",
"drawable",
context.packageName
);
or to get ids of image views like so:
int resId = context.resources.getIdentifier(
"image${position}",
"id",
context.packageName
);
Once you have the id's you could load drawables or views how you normally would with findViewById(resId) or ContextCompat.getDrawable(context, resId)
Make sure to call findViewById() on the parent of the view you are trying to find.

Related

Can't dynamically change ImageView by code

I would like to understand, why I can't dynamically change the drawable resource from my imageView.
I have different use cases, and in function of these use cases I have to change my imageView. In my code I tried these solutions below, but I can't get my imageView refresh. It keeps the default drawable resource defined first. Here what I tried:
int imgRes = activity.getResources().getIdentifier("packageName:drawable/"+"my_drawable_name", null, null);
OR
int imgRes = activity.getResources().getIdentifier("drawable/"+"my_drawable_name", "drawable", activity.getPackageName());
imageIcon.setImageResource(imgRes);
imageIcon.invalidate();
And also:
imageIcon.setImageDrawable(null);
imageIcon.setImageDrawable(activity.getResources().getDrawable(R.drawable.my_drawable_name));
imageIcon.invalidate();
I'm in one adapter and I passed this ImageView from my activity to my adapter. And I'm doing this operation from this adapter which go the instance of my imageView.
So I tried to change this resource my_drawable_name but in both cases above, my imageView is never updated/refresh, and its image resource doesn't change. I have no error it just doesn't work. Am I doing something wrong ? What's the best practice to dynamically change a resource from an imageview by code?
No need to append drawable directory. It is the default behavior of android to get best suited drawable according to device.
Try using following code:
int imgRes = activity.getResources().getIdentifier("my_drawable_name", "drawable", activity.getPackageName());
try imageIcon.setImageResource(R.drawable.my_drawable_name);

how to load images from resources

How can I load images from resource folder in my GridView Adapter ?
I have a 200 images in resource folder i named them as name_1.png,name_2.png.
I want to load image and text view into android gridview element and show the images according to the number from resource folder.
I am able to show the text view data but not the images.
can any one suggest me how to do this. I am thinking that I have to write code in getview method to change the image.
This is getview method that I tried
Put your images into drawable folder and reach them by name, then you access them by name.
int resourceId = context.getResources().getIdentifier(name, "drawable",
context.getPackageName());
Then you can use the resource
imageView.setImageResource(resourceId);
or
imageView.setBackgroundResource(resourceId);
just a convenient refactoring of the accepted answer if you use kotlin and like using its extensions functions:
fun ImageView.loadDrawableFromName(name:String, ctx: Context, visible:Int=View.VISIBLE){
val resId = ctx.resources.getIdentifier(name, "drawable", ctx.packageName)
this.setImageResource(resId)
this.visibility = visible
}
you can call it in both ways:
imgname="IMGNAME"
myimageview.loadDrawableFromName(imgname, ctx)
and
imgname="IMGNAME"
myimageview.loadDrawableFromName("#drawable/$imgname", ctx)

How to set ImageView using the name String of the local resource avoiding conditional mapping of resources

I want to set an ImageView programatically, passing the name of the local resource drawable as String.
The drawable clearly are int identified in this way
R.drawable.mydrawable_name
How could I do to solve this problem without map everything in a conditional switch?
I want to avoid something in this form
if(myString.equal"stringname_1"){
myImageview.setImageResource( R.drawable.stringname_1);
}
else if(myString.equal"stringname_1")....
etc
You can use getResources().getIdentifier() (http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier(java.lang.String, java.lang.String, java.lang.String)) for this purpose. For your code it would look something like this:
int id = getResources().getIdentifier(myString, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);
myImageview.setImageDrawable(drawable);
The code above assumes you're in an Activity.
You can do it using java reflection
Field field = R.drawable.class.getDeclaredField("mydrawable_name");
int a = field.getInt(this);
a will have the id value of R.drawable.mydrawable_name . Now you can use this id to set image
Pl Note: Below one is need to be comment for the accepted answer but I dont have previlage to add comment.
getDrawable(id) is deprecated now instead we can use
getDrawable(int id, Resources.Theme theme)
Return a drawable object associated with a particular resource ID and styled for the specified theme.
getTheme return the current theme.
Sample is given below:
Drawable drawable = resources.getDrawable(id, context.getTheme());

Is there a way to set setContentView(int id) dynamically?

I'd like to be able to loop through a list of xml layout files instead of having to specify a particular one in the setContentView argument.
Obviously the types are incorrect, but something like:
ArrayList<String> pages = new ArrayList<String>();
//(Where each of the xml pages are stored like R.layout.page1, R.layout.page2, etc)
setContentView(pages.get(0));
Is this possible somehow?
You should use the ViewFlipper widget instead. Here is an example.
It is cleaner to manage the content views and their children widgets this way.
Anyway, the resource IDs can be obtained from names using the Resources.getIdentifier method.
Yes. it's possible. But two notes:
The ids are ints, not Strings.
You need to manage the views inside them properly.
In an application I have created I use the following code to set the image button to a particular resource:
imgBtnCard.setImageResource(this.getResources()
.getIdentifier("com.twp.cptshitface:drawable/" +
cardType + cardDetails[1] , null, null));
I would say that this is what you are looking for:
int resLayoutId = this.getResources().
getIdentifier("your.package.namespace:layout/" +
pages.get(0), null, null);
setContentView(resLayoutId);
// where pages.get(0) returns a string such as "main2"
I've quickly tested this code in the onCreateMethod.
remember to clean your project if you add more layouts and/or resources so the id's are updated!

dynamically add array of buttons and reference those buttons by id in android

i found this helpful post for adding buttons dynamically to a layout, however i am can't understand how to reference those buttons by id (or some other way) to use them in the program. can anyone help me?
In code why don't you just declare a class level variable? Another common technique is to save references as tags or save whole bunch of references in the holder object and save that as a tag
I had the same situation.Just use Tag, and assign them an id that you can use in a loop. See example below for some images and assignment of tags and touch listener, but you can you it for buttons or anything you want. Now you can use loops to change things about each button:
for (int i = 0; i < 8; i++)
{
String bid = "WLButton"+i;
int resID = getResources().getIdentifier(bid, "id", "com.head");
wlbutt[i] = (ImageView) findViewById(resID);
wlbutt[i].setTag(i);
wlbutt[i].setOnTouchListener((OnTouchListener) WLListener);
}

Categories

Resources