我如何在Kotlin中绘制图片?

问题描述 投票:1回答:1

我正在Android Studio中从事一个小项目。我已将drawable添加到res / drawable文件夹。enter image description here

但是我无法从代码中获取它。我尝试了不同的方法:

ContextCompat.getDrawable(getActivity(), R.drawable.ic_training);

val drawable: Drawable? = ContextCompat.getDrawable(context.applicationContext, R.drawable.ic_training )
val drawable2: Drawable = R.drawable.ic_training

它们都返回错误的未解决引用。这是我的XML文件:

<vector
        android:id = "@+id/ic_training"
        android:alpha="0.85" android:height="24dp"
    android:viewportHeight="24.0" android:viewportWidth="24.0"
    android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="ic_training"    >
    <path android:fillColor="#FF000000" android:pathData="M22,21c-1.11,0 -1.73,-0.37 -2.18,-0.64 -0.37,-0.22 -0.6,-0.36 -1.15,-0.36 -0.56,0 -0.78,0.13 -1.15,0.36 -0.46,0.27 -1.07,0.64 -2.18,0.64s-1.73,-0.37 -2.18,-0.64c-0.37,-0.22 -0.6,-0.36 -1.15,-0.36 -0.56,0 -0.78,0.13 -1.15,0.36 -0.46,0.27 -1.08,0.64 -2.19,0.64 -1.11,0 -1.73,-0.37 -2.18,-0.64 -0.37,-0.23 -0.6,-0.36 -1.15,-0.36s-0.78,0.13 -1.15,0.36c-0.46,0.27 -1.08,0.64 -2.19,0.64v-2c0.56,0 0.78,-0.13 1.15,-0.36 0.46,-0.27 1.08,-0.64 2.19,-0.64s1.73,0.37 2.18,0.64c0.37,0.23 0.59,0.36 1.15,0.36 0.56,0 0.78,-0.13 1.15,-0.36 0.46,-0.27 1.08,-0.64 2.19,-0.64 1.11,0 1.73,0.37 2.18,0.64 0.37,0.22 0.6,0.36 1.15,0.36s0.78,-0.13 1.15,-0.36c0.45,-0.27 1.07,-0.64 2.18,-0.64s1.73,0.37 2.18,0.64c0.37,0.23 0.59,0.36 1.15,0.36v2zM22,16.5c-1.11,0 -1.73,-0.37 -2.18,-0.64 -0.37,-0.22 -0.6,-0.36 -1.15,-0.36 -0.56,0 -0.78,0.13 -1.15,0.36 -0.45,0.27 -1.07,0.64 -2.18,0.64s-1.73,-0.37 -2.18,-0.64c-0.37,-0.22 -0.6,-0.36 -1.15,-0.36 -0.56,0 -0.78,0.13 -1.15,0.36 -0.45,0.27 -1.07,0.64 -2.18,0.64s-1.73,-0.37 -2.18,-0.64c-0.37,-0.22 -0.6,-0.36 -1.15,-0.36s-0.78,0.13 -1.15,0.36c-0.47,0.27 -1.09,0.64 -2.2,0.64v-2c0.56,0 0.78,-0.13 1.15,-0.36 0.45,-0.27 1.07,-0.64 2.18,-0.64s1.73,0.37 2.18,0.64c0.37,0.22 0.6,0.36 1.15,0.36 0.56,0 0.78,-0.13 1.15,-0.36 0.45,-0.27 1.07,-0.64 2.18,-0.64s1.73,0.37 2.18,0.64c0.37,0.22 0.6,0.36 1.15,0.36s0.78,-0.13 1.15,-0.36c0.45,-0.27 1.07,-0.64 2.18,-0.64s1.73,0.37 2.18,0.64c0.37,0.22 0.6,0.36 1.15,0.36v2zM8.67,12c0.56,0 0.78,-0.13 1.15,-0.36 0.46,-0.27 1.08,-0.64 2.19,-0.64 1.11,0 1.73,0.37 2.18,0.64 0.37,0.22 0.6,0.36 1.15,0.36s0.78,-0.13 1.15,-0.36c0.12,-0.07 0.26,-0.15 0.41,-0.23L10.48,5C8.93,3.45 7.5,2.99 5,3v2.5c1.82,-0.01 2.89,0.39 4,1.5l1,1 -3.25,3.25c0.31,0.12 0.56,0.27 0.77,0.39 0.37,0.23 0.59,0.36 1.15,0.36z"/>
    <path android:fillColor="#FF000000" android:pathData="M16.5,5.5m-2.5,0a2.5,2.5 0,1 1,5 0a2.5,2.5 0,1 1,-5 0"/>
</vector>
android kotlin drawable android-resources
1个回答
0
投票

在您的活动中做

val drawble = this.resources.getDrawable(R.drawable. ic_training,theme)

如果在片段中

val drawble = context!!.resources.getDrawable(R.drawable.ic_training,context!!.theme)
© www.soinside.com 2019 - 2024. All rights reserved.