如何从XML矢量图设置Drawable到ImageSpan中

7

如何在ImageSpan中使用来自xml矢量图的Drawable? 我使用了以下两种方法。 但是我的图标没有显示出来。 当我使用来自drawable资源的png时,图标会显示出来。 有什么想法吗?

private void setupEmptyListInfoBox() {
        Drawable icon = loadVectorFromResources(getActivity(), R.drawable.ic_add_circle_24dp);
        ImageSpan is = new ImageSpan(icon, DynamicDrawableSpan.ALIGN_BASELINE);
        String info = getString(R.string.empty_weight_list_info);
        int iconPosition = info.indexOf("|");

        SpannableString text = new SpannableString(info);
        text.setSpan(is, iconPosition, iconPosition + 1, 0);

        mEmptyListInfo.setText(text);
    }

public static Drawable loadVectorFromResources(Context context, int resId) {
    Drawable drawable;
    if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        drawable = VectorDrawableCompat.create(context.getResources(), resId, context.getTheme());
    } else {
        drawable = context.getResources().getDrawable(resId, context.getTheme());
    }
    return drawable;
}

只是想知道,你是否尝试将它放入 XML 中检查其在非编程环境下是否可用? - user6547359
@user6547359 向量图是正确的,在 XML 中可以使用,例如在 TextView 中使用 android:drawableTop="@drawable/ic_add_circle_24dp"。我是从向量资源(Android Studio)中创建它的。 - kazhiu
3
试着看一下这个链接:https://dev59.com/Y3A75IYBdhLWcg3wqK7_,也许只是一个边界问题。 - user6547359
1
@user6547359 setBounds工作得很好,图标显示出来了,谢谢! - kazhiu
@user6547359,谢谢。你救了我的一天。 - 正宗白布鞋
1个回答

4
我刚刚成功将一个向量加载到一个 ImageSpan 中,方法如下:
Drawable myDrawable = AppCompatResources.getDrawable(context, R.drawable.my_drawable);
myDrawable.setBounds(0, 0, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());

ImageSpan myImageSpan = new ImageSpan(myDrawable, ImageSpan.ALIGN_BASELINE);
SpannableString mySpannableString = new SpannableString(context.getString(R.string.my_string));
mySpannableString.setSpan(myImageSpan, 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

希望这可以帮助您。

图标具有父布局的最大宽度和高度,使用此代码,setBounds即使我像setBound(0,0,20,20)这样做,也不起作用。你有解决办法吗?我们如何缩放矢量XML可绘制对象? - CDrosos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接