当format="时,在customview-kotlin类中获取attrs值;参考文献"



我已经创建了一个CustomView类,我想在其中动态地获取drawable。因此创建了attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="myImage" format="reference"/>
</declare-styleable>
</resources>

然后通过如下xml文件设置这个属性:

<com.example.myapplication.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:myImage="@drawable/my_icon"/>

现在我想在我的CustomView类中获得这个myImage值,我该如何获得它?

我已经尝试了很多方法通过TypedValue和TypedArray获得它,但都无法获得

val typedValue = TypedValue()
context.theme.resolveAttribute(R.attr.myImage, typedValue, true)
val imageResId = ContextCompat.getDrawable(context,typedValue.resourceId)

val typedArray =
context.theme.obtainStyledAttributes(attrs, R.styleable.CustomView, 0, 0)
val imageResId = typedArray.getResourceId(R.styleable.CustomView_myImage,0)

您差不多到了,这是一个工作代码:

val typedArray = context.obtainStyledAttributes(it, R.styleable.CustomView, 0, 0)
val image = typedArray.getResourceId(R.styleable.CustomView_ myImage, -1) // the -1 parameter could be your placeholder e.g. R.drawable.placeholder_image

然后你就有了可以使用的绘图资源,例如:

imageView.setImageDrawable(ContextCompat.getDrawable(context, image))

或者如果你想直接拨打可提取电话:

val image = typedArray.getDrawable(R.styleable.CustomView_myImage)

但请记住,这样你的dravable可能是null。

享受编码!

最新更新