当format=“reference”时,在customview kotlin类中获取attrs值
我创建了一个 CustomView 类,我想在其中动态获取可绘制对象。因此,为此创建了 attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="myImage" format="reference"/>
</declare-styleable>
</resources>
然后通过 xml 文件设置此 attrs,如下所示:
<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)
I have created one CustomView class where I want to get drawable dynamically. So for that have created attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="myImage" format="reference"/>
</declare-styleable>
</resources>
And then set this attrs through xml file like below:
<com.example.myapplication.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:myImage="@drawable/my_icon"/>
Now I want to get this myImage
value in my CustomView
class how can i get it?
I have already tried many ways to get it by TypedValue and TypedArray but not able to get it.
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你就快到了,这是一个工作代码:
然后你就有了可以使用的可绘制资源,例如:
或者如果你想直接调用可绘制对象:
但请记住,这样你的可绘制对象可能为空。
享受编码的乐趣!
You are almost there, this is a working code:
and then you have the resource of your drawable that you can work with, as for the example:
or if you would like to get a drawable directly call:
but remember that this way your drawable might be null.
Enjoy coding!