安卓布局中使用html,android – 在布局绑定中使用属性资源(?attr /)?

如果@ {android.R.attr.textColorPrimary}解析为Java中的android.R.attr.textColorPrimary的值,则需要做的就是将其解析为颜色.

有一个设置进入这个.

ContextUtils.java

以下方法将上下文的主题和可选样式的提供的attr解析为颜色.如果出现错误,则返回到后备颜色.

@ColorInt

public static int resolveColor(final Context context, @StyleRes final int style, @AttrRes final int attr, @ColorInt final int fallback) {

final TypedArray ta = obtainTypedArray(context, style, attr);

try {

return ta.getColor(0, fallback);

} finally {

ta.recycle()

}

}

@ColorInt

public static int resolveColor(final Context context, @AttrRes final int attr, @ColorInt final int fallback) {

return resolveColor(context, 0, attr, fallback);

}

有效实现上述目标的实用方法.

private static TypedArray obtainTypedArray(final Context context, @StyleRes final int style, @AttrRes final int attr): TypedArray {

final int[] tempArray = getTempArray();

tempArray[0] = attr;

return context.obtainStyledAttributes(style, tempArray);

}

private static final ThreadLocal TEMP_ARRAY = new ThreadLocal<>();

private static final int[] getTempArray() {

int[] tempArray = TEMP_ARRAY.get();

if (tempArray == null) {

tempArray = int[1];

TEMP_ARRAY.set(tempArray);

}

return tempArray;

}

更复杂的代码在my android-commons library(这部分写在科特林,拿你需要的).

Bindings.java

以下是如何使用它:

@BindingAdapter({"bind:htmlTextColor"})

public static void setHtml(final WebView webView, @AttrRes final int textColorAttr) {

final Context context = webView.getContext();

final int textColor = ContextUtils.resolveColor(context, textColorAttr, Color.BLACK);

// binding logic

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值