【问题标题】:How to obtain a Drawable (with drawable alias) using TypedArray如何使用 TypedArray 获取可绘制对象(带有可绘制别名)
【发布时间】:2014-09-29 18:21:53
【问题描述】:

因此,根据 Android 文档,Resources.getDrawable() 在 Jelly Bean 之前的 OS 版本中存在一个已知错误,其中别名 drawable 无法以正确的密度解析(因此 drawable-hdpi 中的 100px 图像在HDPI 设备):

注意:在 JELLY_BEAN 之前,当此处传递的资源 ID 是另一个 Drawable 资源的别名时,此函数将无法正确检索最终配置密度。这意味着如果别名资源的密度配置与实际资源不同,则返回的 Drawable 的密度将不正确,从而导致缩放不良。要解决此问题,您可以改为通过 TypedArray.getDrawable 检索 Drawable。将 Context.obtainStyledAttributes 与包含感兴趣的资源 ID 的数组一起使用来创建 TypedArray。

但是,我无法使用指定的说明实际解析Drawable。我写的一个实用方法:

@NonNull
public static Drawable resolveDrawableAlias(@NonNull Context ctx, @DrawableRes int drawableResource) {
    final TypedArray a = ctx.obtainStyledAttributes(new int[] { drawableResource });
    final Drawable result = a.getDrawable(0);
    a.recycle();
    return result;
}

当我为可绘制别名传递资源 ID 时,总是返回 null,我在 res/values/drawables.xml 中将其定义为:

<item name="my_drawable" type="drawable">@drawable/my_drawable_variation</item>

我在这里遗漏了什么,或者其他一些解决方法吗?

编辑:我在下面添加了一个解决方案。

【问题讨论】:

标签: android android-resources android-drawable


【解决方案1】:

好的,我找到了以下似乎可以解决问题的解决方案:

/**
 * Method used as a workaround for a known bug in 
 * {@link android.content.res.Resources#getDrawable(int)}
 * where the density is not properly resolved for Drawable aliases 
 * on OS versions before Jelly Bean.
 *
 * @param ctx a context for resources
 * @param drawableResource the resource ID of the drawable to retrieve
 *
 * @return the Drawable referenced by drawableResource
 */
@NonNull
public static Drawable resolveDrawableAlias(@NonNull Context ctx, @DrawableRes int drawableResource) {
    final TypedValue value = new TypedValue();

    // Read the resource into a TypedValue instance, passing true
    // to resolve all intermediate references
    ctx.getResources().getValue(drawableResource, value, true);
    return ctx.getResources().getDrawable(value.resourceId);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2012-09-05
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多