How to Set an Imageview's Image from a String

How to set an imageView's image from a string?

if you have the image in the drawable folder you are going about this the wrong way.

try something like this

Resources res = getResources();
String mDrawableName = "logo_default";
int resID = res.getIdentifier(mDrawableName , "drawable", getPackageName());
Drawable drawable = res.getDrawable(resID );
icon.setImageDrawable(drawable );

Android Setting image from string

Correct :

  <ImageView  
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image1"
android:src="@drawable/no_image" />

Place this line in onCreate Method of your Activity :

ImageView lblPic = (ImageView) findViewById(R.id.image1);
int resID = getResources().getIdentifier(imagename, "drawable", getPackageName());
lblPic.setImageResource(resID);

How to change an ImageView with a filename

Please see Android, reference things in R.drawable. using variables?

//to retrieve image in res/drawable and set image in ImageView
String imageName = "picture"
int resID = getResources().getIdentifier(imageName, "drawable", "package.name");
ImageView image;
image.setImageResource(resID );

Android: How to set the ImageView src from string?

I think your approach is a bad idea.

You can localize a drawable too. I think this is the better approach for changing images when localizing your app.

how to set imageview from Mysql in adapter using string value

Try Glide for this purpose :

Glide.with(this).load(motorType.getImage()).into(holder.imageView);

In gradle :

compile 'com.github.bumptech.glide:glide:4.6.1'

For Picasso use :

Picasso.with(this).load(motorType.getImage()).into(holder.imageView);

how to set a variable imageview src?

Use the following code to access drawable resources using name:

    Resources resources = getResources();
final int resourceId = resources.getIdentifier("two_of_diamonds",
"drawable", getPackageName());

imgView.setImageResource(resourceId);

Java ImageView string as src

You can't have src as string in xml.

but you write your own code in your calling activity to set image source using string resourse.
for this you have to put your image file in asset , and you can refer below code

    ImageView view  = findViewById(R.id.imageLogo);
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
//R.string.yourstring will be like "sample.png"
istr = assetManager.open(getResources().getString(R.string.yourstring));
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(istr);
view.setImageBitmap(bitmap);


Related Topics



Leave a reply



Submit