Skip to content
Advertisement

setImageResource() with attrs value

I’m trying to put an image to my ImageView, with a custom attribute defined by me, I’m doing it this way:

Attrs:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <declare-styleable name="MyAttr">
        <attr name="my_image" format="reference"/>
    </declare-styleable>
</resources>

ImageView Attrs:

app:my_image="@drawable/image"

Than in my View:

int imageSrc;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyAttr, 0, 0);
try {
    imageSrc = ta.getResourceId(R.styleable.MyAttr_my_image, -1);
} finally {
    ta.recycle();
}

And set the image to the ImageView with:

imageView.setImageResource(imageSrc);

But nothing appears, I’ve tried also with:

imageSrcDrawable = ta.getDrawable(R.styleable.MyAttr_my_image);

And:

if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    imageView.setBackgroundDrawable(imageSrcDrawable);
} else {
    imageView.setBackground(imageSrcDrawable);
}

UPDATE:

I’ve already tried to parse attribute with ta.getInt(..) and its work fine!

I can not understand why, thanks in advance!

Advertisement

Answer

It would have been useful if you had included the Layout XML code, however, I’m going to take a stab in the dark and suggest you might have a problem with the name-spacing. Have you defined the namespace in your Layout XML as

xmlns:whatever="http://schemas.android.com/apk/res/com.yourcompany.yourpackage"

If not, I’d give that a spin. Other suggestions:

I believe that obtainStyledAttributes actually resolves all the attributes when you call it on the AttributeSet. So, I wouldn’t be surprised if the TypedArray instance already contains the resolved resource id, in short: try and use

imageSrc = ta.getInt(R.styleable.MyAttr_my_image, -1);

as opposed to ta.getResourceId(). And finally, if all the above fails, I would try and use ta.hasValue(R.styleable.MyAttr_my_image) do determine if the value actually exist, if not, then atleast you know that obtainStyledAttributes didn’t successfully parse and resolve the attribute, and thus, you can start looking into why. As in, file locations, namespaces etc.

Hope you get it working.

EDIT:

After reading your comments, I only got one last question, from the snippets above, I can’t see which method you are actually initialising this in, and I’m wondering if your image view is being redrawn afterwards. I’m presuming that imageView.setImageResource(imageSrc); invalidates the imageView, however, since its now showing up, and you just confirmed that your 100% sure that it loaded correctly, then it might we worth invalidating it manually, just to check, that is trying a imageView.invalidate(); after calling image.setImageResource().

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement