具有attrs值的setImageResource()

时间:2016-01-15 21:28:41

标签: java android imageview android-attributes

我正在尝试将图片放到我的ImageView,并使用我定义的自定义属性,我这样做:

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"

比我的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(..)解析属性并且工作正常!

我无法理解为什么,提前谢谢!

2 个答案:

答案 0 :(得分:3)

如果您已经包含了布局XML代码,那将非常有用,但是,我会在黑暗中进行一次尝试,并建议您可能会遇到名称间距问题。您是否已将布局XML中的命名空间定义为

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

如果没有,我会给它一个旋转。其他建议:

我相信obtainStyledAttributes实际上解析了在AttributeSet上调用它时的所有属性。因此,如果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%确定它已正确加载,那么我们可能值得手动使其无效,只是为了检查,即在致电imageView.invalidate();后尝试image.setImageResource()

答案 1 :(得分:0)

在这里试试这个代码

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);