Android Preference With Icon On Right Side of Title (Custom View)

Android Preference support icon on the left side of preference. I wanted to put an icon or badge image on the right side of the Preference's title.

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

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

Create the custom view class. We add Drawable to the right side of by using TextView.setCompoundDrawablesWithIntrinsicBounds.

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 use the custom widget


        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.