2

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!

Michele Lacorte
  • 5,323
  • 7
  • 32
  • 54
  • why dont you just use `android:src="@drawable/image"`? – petey Jan 15 '16 at 21:44
  • Because I need custom attrs for LinearLayout custom class @petey – Michele Lacorte Jan 15 '16 at 21:47
  • 2
    that doesnt really explain why you aren't using the [ImageView xml attr of `android:src`](http://developer.android.com/reference/android/widget/ImageView.html#attr_android:src) and it appears you might be trying to re-invent a wheel android already gave you. If this is not the case, please post your custom LinearLayout class. – petey Jan 15 '16 at 21:52
  • It can be but let's say that I want to do such a thing as I do ? – Michele Lacorte Jan 15 '16 at 21:56
  • 2
    Fair enough, please post the full code of your "custom" View – petey Jan 15 '16 at 22:11
  • I do not think much use. The problem is linked to that, trust me there is nothing that can affect – Michele Lacorte Jan 15 '16 at 22:15

3 Answers3

3

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().

JustDanyul
  • 13,813
  • 7
  • 53
  • 71
  • I've java.lang.NumberFormatException: Invalid int: "res/drawable/image.png" on ta.getInt(...) – Michele Lacorte Jan 17 '16 at 22:40
  • Ok, cool. Was just a thought, at-least now you know that the obtainStyledAttributes is doing its job ;-) – JustDanyul Jan 17 '16 at 22:45
  • I knew this already , that's why I could not understand exactly what it could be!!! – Michele Lacorte Jan 17 '16 at 22:46
  • 1
    we'll it would have been useful if you would have included that information ;-) that you had determined that it was parsed, normally when somebody tried different ways of retrieving data, and setting data. It suggests that he/she isn't sure whats going on. Anyways, are you sure its being redrawn after you set the src? (i'll update my question) – JustDanyul Jan 17 '16 at 22:49
  • tried with invalidate() and postInvalidate() but nothing, if i load with setImageResource(R.drawable.image) it works.. – Michele Lacorte Jan 17 '16 at 22:56
  • Oh..it works! I noticed a little thing in the code that could be detrimental and ineffetti was so ! Thanks again his response was useful to understand the possible dynamics of the incident! – Michele Lacorte Jan 17 '16 at 23:00
0

Try this code here

private int getResourceFromAttr(int attr)
{
    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = getActivity().getTheme();
    theme.resolveAttribute(attr, typedValue, true);
    int res_ = typedValue.resourceId;
    return res_;
}

Then set the Image

    ImageView imageView = findViewById(R.id.main_logo);
    int res = getResourceFromAttr(R.attr.img_main_logo);
    imageView.setImageResource(res);
Wowo Ot
  • 1,362
  • 13
  • 21
0

I think this will help who may be looking for something simple

<resources>
    <declare-styleable name="ItemView">
        <attr name="icon" format="reference" />
    </declare-styleable>
</resources>
    private fun setLayout(attrs: AttributeSet?) {
            attrs?.let { attributeSet ->
                val attributes = context.obtainStyledAttributes(
                    attributeSet,
                    R.styleable.ItemView
                )
    
                val icon = attributes.getDrawable(R.styleable.ItemView_icon)
    
                binding.itemIcon.setImageDrawable(icon)
    
                attributes.recycle()
            }
        }
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 24 '22 at 12:21