Drawable resource from custom attribute

There is actually an attribute format called "reference". So you will get something like this in your custom views class:

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

While having sometning like this in your attrs.xml:

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

Where "a" is a TypedArray that you get from attributes taken from the views constructor.

There is a good similar answer here: Defining custom attrs


See EdgarK's answer; it's better. (I can't delete this since it's the accepted answer)

Does this answer your question?

"You can use format="integer", the resource id of the drawable, and AttributeSet.getDrawable(...)."

(From https://stackoverflow.com/a/6108156/413254)


I used this and it works for kotlin (editted to paste the full class )

class ExtendedFab(context: Context, attrs: AttributeSet?) :
LinearLayout(context, attrs) {

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()
    }
}

/**
 * Sets a string in the button
 * @param[text] label
 */
fun setText(text: String?) {
    tvFabLabel.text = text
}

/**
 * Sets an icon in the button
 * @param[icon] drawable resource
 */
fun setIcon(icon: Drawable?) {
    ivFabIcon.setImageDrawable(icon)
}
}

Using this attributes

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

And this is the layout

 <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" />