How to create Drawable from resource - android

I have an image res/drawable/test.png (R.drawable.test).
I want to pass this image to a function which accepts Drawable, e.g. mButton.setCompoundDrawables().
So how can I convert an image resource to a Drawable?

Your Activity should have the method getResources. Do:
Drawable myIcon = getResources().getDrawable( R.drawable.icon );
As of API version 21 this method is deprecated and can be replaced with:
Drawable myIcon = AppCompatResources.getDrawable(context, R.drawable.icon);
If you need to specify a custom theme, the following will apply it, but only if API is version 21 or greater:
Drawable myIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.icon, theme);

This code is deprecated:
Drawable drawable = getResources().getDrawable( R.drawable.icon );
Use this instead:
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);

The getDrawable (int id) method is deprecated as of API 22.
Instead you should use the getDrawable (int id, Resources.Theme theme) for API 21+
Code would look something like this.
Drawable myDrawable;
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
myDrawable = context.getResources().getDrawable(id, context.getTheme());
} else {
myDrawable = context.getResources().getDrawable(id);
}

I would just like to add that if you are getting "deprecated" message when using getDrawable(...) you should use the following method from the support library instead.
ContextCompat.getDrawable(getContext(),R.drawable.[name])
You do not have to use getResources() when using this method.
This is equivalent to doing something like
Drawable mDrawable;
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
mDrawable = ContextCompat.getDrawable(getContext(),R.drawable.[name]);
} else {
mDrawable = getResources().getDrawable(R.id.[name]);
}
This works on both pre and post Lollipop versions.

Get Drawable from vector resource irrespective of, whether its vector or not:
AppCompatResources.getDrawable(context, R.drawable.icon);
Note:
ContextCompat.getDrawable(context, R.drawable.icon); will produce android.content.res.Resources$NotFoundException for vector resource.

If you are trying to get the drawable from the view where the image is set as,
ivshowing.setBackgroundResource(R.drawable.one);
then the drawable will return only null value with the following code...
Drawable drawable = (Drawable) ivshowing.getDrawable();
So, it's better to set the image with the following code, if you wanna retrieve the drawable from a particular view.
ivshowing.setImageResource(R.drawable.one);
only then the drawable will we converted exactly.

If you are inheriting from a fragment you can do:
Drawable drawable = getActivity().getDrawable(R.drawable.icon)

You must get it via compatible way, others are deprecated:
Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.my_drawable, null);

In Kotlin you can do like this:
binding.floatingActionButton.setImageDrawable(
AppCompatResources.getDrawable(this, android.R.drawable.ic_delete))
Where binding is a root View and this refer to Context, You need import
import androidx.appcompat.content.res.AppCompatResources

Related

Is there a performance impact on changing color of vector drawables programmatically?

I am using a vector drawable in my code. Based on some condition I need to change the color of the drawable. Using below code to achieve it.
Drawable drawable = VectorDrawableCompat.create(context.getResources(),
R.drawable.icon_vector_star, null);
if(drawable != null) {
drawable = drawable.mutate();
drawable = DrawableCompat.wrap(drawable);
//Change the tint to grey to mark it disabled.
DrawableCompat.setTint(drawable,
ContextCompat.getColor(context, R.color.grey));
DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_IN);
imageView.setImageDrawable(drawable);
} else {
Log.e(LOG_TAG, "Error while creating vector drawable");
}
Is there a performance impact while doing this? Should I use another vector
drawable of different color and simply set it? Please suggest.

How to set drawableRIGHTon Android button?(IMAGE DINAMICALLY)

Drawable drawable = res.getDrawable(R.drawable.image);
button.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
This work but i would all dinamically.
Drawable drawable = res.getDrawable(R.drawable.path);
button.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
where path is a string that contains a name of image..
thanks to all!
If I got you right, you are trying to get drawable by the image name. right?
If so,
int imageResource = res.getIdentifier(path, "drawable", getContext().getPackageName());
Drawable drawable = res.getDrawable(imageResource);
then assign the button drawable...

get ImageView src programmatically

How to get ImageView src programmatically and set it in another ImageView
Drawable drawable = imageViewA....?
imageViewB.setImageDrawable(drawable);
You can do something like this:
Drawable drawable = imageViewA.getDrawable();
if(drawable != null){
imageViewB.setImageDrawable(drawable);
}
You can use setImageResource(int)
imageView.setImageResource(R.drawable.bg_image);
Instead of get drawable you do...
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
and set to new image
newImageView.setImageBitmap(bitmap);

How to retrieve drawable from attributes reference

I defined theme and style inside my app. icons (drawable) are defined using reference in style file as
<attr name="myicon" format="reference" />
and style as
<style name="CustomTheme" parent="android:Theme.Holo">
<item name="myicon">#drawable/ajout_produit_light</item>
I need to retrieve the drawable programmatically to use the good image in a dialogfragment.
If I make like
mydialog.setIcon(R.style.myicon);
I get an id equals to 0, so no image
I tried to use something like
int[] attrs = new int[] { R.drawable.myicon};
TypedArray ta = getActivity().getApplication().getTheme().obtainStyledAttributes(attrs);
Drawable mydrawable = ta.getDrawable(0);
mTxtTitre.setCompoundDrawables(mydrawable, null, null, null);
I tried different things like that but result is always 0 or null :-/
How I can I do this ?
I found the solution on
Access resource defined in theme and attrs.xml android
TypedArray a = getTheme().obtainStyledAttributes(R.style.AppTheme, new int[] {R.attr.homeIcon});
int attributeResourceId = a.getResourceId(0, 0);
Drawable drawable = getResources().getDrawable(attributeResourceId);
Kotlin solution:
val typedValue = TypedValue()
context.theme.resolveAttribute(R.attr.yourAttr, typedValue, true)
val imageResId = typedValue.resourceId
val drawable = ContextCompat.getDrawable(context, imageResId) ?: throw IllegalArgumentException("Cannot load drawable $imageResId")
With the assumption your context (activity) is themed the way you want it, you can use resolveAttribute on the theme:
TypedValue themedValue = new TypedValue();
this.getTheme().resolveAttribute(R.attr.your_attribute, themedValue, true);
myView.setBackgroundResource(themedValue.resourceId);
So in your case it would look something like this:
TypedValue themedValue = new TypedValue();
this.getTheme().resolveAttribute(R.attr.myicon, themedValue, true);
Drawable mydrawable = AppCompatResources.getDrawable(this, themedValue.resourceId);
mTxtTitre.setCompoundDrawables(mydrawable, null, null, null);
In the examples this would be your activity. If you're not in an activity get a valid context.
It would seem as though you are trying to set the icon of your myDialog using a resource and are trying to access it through R.style but your other code segment leads me to believe that you have the resource located in R.drawable
With that in mind you should be able to get the effect you want with myDialog.setIcon(R.drawable.myicon);

Android - How to show images from resources drawable?

I'm not able to show an image which is saved in res/drawable folder.
I use ImageGetter to do this. The code is below:
ImageGetter imageGetter3 = new ImageGetter() {
public Drawable getDrawable(String source) {
int id=0;
if (source.equals("smiley")) {
id = R.drawable.smiley;
}
Drawable d = getResources().getDrawable(id);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
};
directions += "Je bent bij lokaal " + vertrek.getNaam() + "\n"
+ "Sta met je rug voor de deur\n"
+ Html.fromHtml("<img src=\"smiley\">", imageGetter3, null) + " Draai naar links\n";
What I see on the screen when running is a little square with "obj" text on it.
So what is wrong? The image cannot be read or something else?
How to show images?
Honestly I have Googled a lot and tried other methods of ImageGetter as well, but none of them seems to work, I tried these too, they don't work:
ImageGetter imageGetter2 = new ImageGetter() {
public Drawable getDrawable(String source) {
Drawable d = null;
d = Drawable.createFromPath(source);
d.setBounds(0,0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
};
ImageGetter imageGetter = new ImageGetter() {
public Drawable getDrawable(String source) {
Drawable drawFromPath;
int path = Route.this.getResources().getIdentifier(source, "drawable","com.prj56.tracingapp");
drawFromPath = (Drawable) Route.this.getResources().getDrawable(path);
drawFromPath.setBounds(0, 0, drawFromPath.getIntrinsicWidth(), drawFromPath.getIntrinsicHeight());
return drawFromPath;
}
};
=========================================================
if (....) {
ImageView iv1 = new ImageView(this);
iv1.setImageResource(R.drawable.smiley);
directions += "Je bent bij lokaal " + vertrek.getNaam() + "\n"
+ "Sta met je rug voor de deur\n";
HERE COMES THE IMAGE! BUT HOW TO DO THIS? It's within directions textview...
directions += " Draai naar links\n";
}
Update 12 Dec 2016:
getResources().getDrawable() was deprecated in api 22 so you should now be using ContextCompat.getDrawable e.g.
Drawable d = ContextCompat.getDrawable(context, R.drawable.smiley);
In your activity you can call this to get your Drawable resource as a Drawable object
Drawable d = getResources().getDrawable(R.drawable.smiley);
If you want to show your drawable in an ImageView you can do this:
ImageView i = new ImageView(this);
i.setImageResource(R.drawable.smiley);
or in your xml file
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/smiley"/>
You can get the image with the help of pImg.Based on the adapter position get the string that is the image name.The image should be present in the drawable folder.
ImageView prodImg=(ImageView)view.findViewById(R.id.img_proj_name);
String pImg=prod.get(position);
int resID = view.getResources().getIdentifier("#drawable/"+pImg , "drawable", parentView.getContext().getPackageName());
prodImg.setImageResource(resID);
A super easy way to show it is to write this in your ImageView widget in your xml:
android:background="#drawable/your_file_name"
... and make sure you have put that image file (whether png or jpg, etc.) into your drawable folder. When you write your_file_name, you only need the title, not the file extension.
I prefer this way over programmatically writing in your .java file (as shown with other answers above), because your xml will show you the image in preview, programmatically will not, it will just show the ImageView placeholder.
Easiest way - Can be consider the below code
We can take advantage of Imageview setImageResource , refer below code for the same.
put image in the drawable like the below order
image_1.png, image_2.png, etc.
int resId = getResources().getIdentifier("image_" + imagePosition, "drawable", getPackageName());
imageview.setImageResource(resId);
Drawable drawable = getResources().getDrawable(R.mydrawableID);
Now you can use it as Image, Like:-
ImageView myImage = findViewById(R.id.yourImageView);
Now fire this -
myImage.setImageResource(drawable);
You should use ContextCompat for backward compatibility features on Android.
//Using ButterKnife
#BindView(R.id.DogImg)
ImageView myImage;
//Or
ImageView myImage = findViewById(R.id.MyImage);
...
Drawable MyImageDrw = ContextCompat.getDrawable(context,R.drawable.myImageOnResources);
myImage.setImageDrawable(MyImageDrw);

Categories

Resources