【发布时间】:2015-08-27 19:08:00
【问题描述】:
我的这个功能在 Android 4.4.1 上运行良好,但在 5.0+ 上会中断。
public static SpannableStringBuilder prependImage(Drawable drawable, String text) {
SpannableStringBuilder builder = new SpannableStringBuilder(" " + text);
builder.setSpan(new ImageSpan(drawable), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return builder;
}
我是这样使用它的:
class MyButton extends Button {
// ... snip ...
setText(
prependImage(
getDrawable(imageResource, color),
getContext().getString(stringResource)),
BufferType.SPANNABLE);
这里是上面引用的getDrawable()方法:
private Drawable getDrawable(int resource, int color) {
final Resources resources = getContext().getResources();
Drawable drawable = resources.getDrawable(resource);
if (drawable != null) {
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}
return drawable;
}
当我调试时,一切似乎都成功了,但没有绘制图像。有什么想法我可能做错了吗?
【问题讨论】:
-
我创建了一个
extends android.widget.Button的类,尝试在运行 KitKat 的模拟器上使用您的prependImage(Drawable, String)方法,但图像未绘制。 -
嗯,应该有办法让它同时利用两者。我很高兴能把它扔掉,去做别的事情。您是否确定将可绘制对象的边界设置为 0,0,0,0 以外的值?
-
@i_am_jorf 您可以使用
TextView而不是Button。在所有 android 版本中,TextView似乎都可以正常工作。 -
在装有 Android 5.1.1 的 Nexus 5 上工作。你在哪里测试它?
-
我正在三星 S6 (5.1) 和 S4 (4.4) 上进行测试。