带有 attrs 值的 setImageResource()

setImageResource() with attrs value

我正在尝试使用我定义的自定义属性将图像放入我的 ImageView,我是这样做的:

属性:

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

ImageView 属性:

app:my_image="@drawable/image"

比我的 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();
}

并将图像设置为 ImageView 并使用:

imageView.setImageResource(imageSrc);

但什么也没有出现,我也试过:

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

并且:

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

更新:

我已经尝试用 ta.getInt(..) 解析属性并且它工作正常!

我不明白为什么,先谢谢了!

如果您包含了布局 XML 代码,它会很有用,但是,我将在黑暗中尝试并建议您可能对 name-spacing 有疑问.您是否在布局 XML 中将命名空间定义为

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

如果没有,我会试一试。其他建议:

我相信当您在 AttributeSet 上调用它时,obtainStyledAttributes 实际上会解析所有属性。因此,如果 TypedArray 实例已经包含已解析的资源 ID,我不会感到惊讶,简而言之:尝试使用

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

相对于 ta.getResourceId()。最后,如果以上所有方法都失败了,我会尝试使用 ta.hasValue(R.styleable.MyAttr_my_image) 确定该值是否确实存在,如果不存在,那么至少您知道 obtainStyledAttributes 没有成功解析和解析属性,因此,您可以开始研究原因。如文件位置、命名空间等

希望你能成功。

编辑:

看完你的评论,我只有最后一个问题,从上面的片段中,我看不出你实际上是用哪种方法初始化的,我想知道你的图像视图是否在之后被重绘。我假设 imageView.setImageResource(imageSrc); 使 imageView 无效,但是,既然它现在出现了,并且您刚刚确认您 100% 确定它加载正确,那么我们可能值得手动使其无效,只是为了检查一下,正在调用 image.setImageResource().

后尝试 imageView.invalidate();

在这里试试这个代码

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_;
}

然后设置图片

    ImageView imageView = findViewById(R.id.main_logo);
    int res = getResourceFromAttr(R.attr.img_main_logo);
    imageView.setImageResource(res);