Custom View Example With Custom Drawable Attributes/Parameters (Kotlin)

Apr 17, 2018
Support Vector Drawable and XML Attributes Declaration

Edit /res/values/attrs.xml to specify style name, attribute name and format (use reference for drawable).

NOTE: I have yet to found the full documentation for attribute format, but some clues is available here and here.

<?xml version="1.0" encoding="utf-8"?>
    <declare-styleable name="PreferencesBadge">
        <attr name="badge" format="reference" />

Create the custom view class, using Resources.Theme.obtainStyledAttributes to get the custom attributes.

Use TypedArray.getResourceId to get the resource number and get drawable using AppCompatResources.getDrawable.

NOTE: Resources$NotFoundException will happen if using TypedArray.getDrawable to retrieve vector image.

class BadgePreference : Preference {    private var badge: Drawable? = null    private lateinit var titleView: TextView    constructor(context: Context) : super(context)    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {        val a = context.theme.obtainStyledAttributes(                attrs,                R.styleable.PreferencesBadge,                0, 0)        try {            // Resources$NotFoundException if vector image            // badge = a.getDrawable(R.styleable.PreferencesBadge_badge)            val drawableResId = a.getResourceId(R.styleable.PreferencesBadge_badge, -1);            badge = AppCompatResources.getDrawable(context, drawableResId)        }        finally {            a.recycle()        }    }    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)    override fun onBindView(view: View) {        super.onBindView(view)        titleView = view.findViewById( as TextView        if (badge != null) {            setBadge(badge)        }    }    fun setBadge(badge: Drawable?) {        this.badge = badge        titleView.compoundDrawablePadding = 20        titleView.setCompoundDrawablesWithIntrinsicBounds(null, null, badge, null)    }}

To specify the custom attributes in XML declaration.


        android:title="Export as Text"
        android:summary="Export as data as plain text file. Keep the file safe as it is not encrypted"



❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.