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"?>
<resources>
<declare-styleable name="PreferencesBadge">
<attr name="badge" format="reference" />
</declare-styleable>
</resources>
Create the custom view class. We add Drawable
to the right side of android.R.id.title
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(android.R.id.title) 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
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.mypackage.myapp">
<com.mypackage.myapp.BadgePreference
android:key="@string/pref_key_export_text"
android:title="Export as Text"
android:summary="Export as data as plain text file. Keep the file safe as it is not encrypted"
custom:badge="@drawable/ic_upcoming"
/>
</PreferenceScreen>