0

I have many Images and I would like to write a short-code I just want to change the image name at the runtime and the code should insert the Picture in the correct image I Try like that :

    img1 = (ImageView) findViewById(R.id.imageView_1);
    img2 = (ImageView) findViewById(R.id.imageView_2);
    img3 = (ImageView) findViewById(R.id.imageView_3);
    img4 = (ImageView) findViewById(R.id.imageView_4); }

public void Load_IN_img1(View view) {
    image_x="img1"; 
  Picasso.with(Main.this).load("http://blabla.comimage1.png").into(image_x);  


public void Load_IN_img1(View view) {
    image_x="img2"; 
 Picasso.with(Main.this).load("http://blabla.comimage1.png").into(image_x);  

that means, if i change the string image_x to "img4" so the code should insert the Picture in the wanted image, into img4.

How can I find the image-name at runtime ?

Json
  • 59
  • 3
  • 13

2 Answers2

1

thanks People, after long searching in google, i found the solution here in forum too : enter link description here

public void Load_IN_img1(View view) {    
 String  image_x="imageView1";// variable 
  int id = getResources().getIdentifier(image_x, "id",   
  this.getPackageName()); 
  ImageView img = findViewById(id);
 Picasso.with(Main.this).load("http://blabla.comimage1.png").into(image_x); 
Community
  • 1
  • 1
Json
  • 59
  • 3
  • 13
0

I guess that the perfect way is using view id. Ex: relatedViewId = public static final int value which is defined in R.java

public void loadImage(View view) {
    image_x = (ImageView) findViewById(relatedViewId);
    Picasso.with(Main.this)
    .load("http://blabla.comimage1.png")
    .into(image_x);
}

Additionally, you can use any other way to solve this problem like reflection, String.equals etc.. However, relatedViewId is more performance than others.

Barış Söbe
  • 470
  • 4
  • 7
  • but i have to change the String from time to time. . where can I put my String (imageView-name) in your code ? – Json Apr 06 '17 at 23:53
  • **relatedViewId** is the parameter of the function. `public void loadImage(int relatedViewId) { ImageView relatedView = (ImageView) findViewById(relatedViewId); Picasso.with(Main.this) .load("http://blabla.comimage1.png") .into(relatedView); }` – Barış Söbe Apr 07 '17 at 11:36