自定义属性的可绘制资源

时间:2013-07-29 22:03:14

标签: android xml drawable

是否有可能在某些自定义属性中从drawable文件夹中获取资源,因此我可以写:

<com.my.custom.View
    android:layout_height="50dp"
    android:layout_width="50dp"
    ...
    my_custom:drawableSomewhere="@drawable/some_image" />

然后在我的自定义视图类中使用drawable执行简单操作?

3 个答案:

答案 0 :(得分:45)

实际上有一种名为&#34; reference&#34;的属性格式。因此,您将在自定义视图类中获得类似的内容:

case R.styleable.PMRadiogroup_images:
                    icons = a.getDrawable (attr);
                    break;

虽然在你的attrs.xml中有这样的东西:

<attr name="images" format="reference"/>

&#34; a&#34;是一个TypedArray,您可以从视图构造函数中获取属性。

这里有一个很好的类似答案:Defining custom attrs

答案 1 :(得分:8)

见EdgarK的回答;它更好。 (我不能删除它,因为这是接受的答案)

这是否回答了你的问题?

“您可以使用format =”integer“,drawable的资源ID和AttributeSet.getDrawable(...)。”

(来自https://stackoverflow.com/a/6108156/413254

答案 2 :(得分:1)

我用过它,它适用于Kotlin

    init {

    LayoutInflater.from(context).inflate(R.layout.component_extended_fab, this, true)
    attrs?.let {

        val styledAttributes = context.obtainStyledAttributes(it, R.styleable.ExtendedFab, 0, 0)
        val textValue = styledAttributes.getString(R.styleable.ExtendedFab_fabText)
        val fabIcon = styledAttributes.getDrawable(R.styleable.ExtendedFab_fabIcon)

        setText(textValue)
        setIcon(fabIcon)
        styledAttributes.recycle()
    }
}


fun setText(text: String?) {
    tvFabLabel.text = text
}

fun setIcon(icon: Drawable?) {
    ivFabIcon.setImageDrawable(icon)
}

使用此属性

<declare-styleable name="ExtendedFab">
    <attr name="fabText" format="string" />
    <attr name="fabIcon" format="reference" />
</declare-styleable>

这是布局

 <com.your.package.components.fab.ExtendedFab
        android:id="@+id/efMyButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:elevation="3dp"
        android:clickable="true"
        android:focusable="true"
        app:fabIcon="@drawable/ic_your_icon"
        app:fabText="Your label here" />
相关问题