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"?>
<resources>
<declare-styleable name="PreferencesBadge">
<attr name="badge" format="reference" />
</declare-styleable>
</resources>
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(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 specify the custom attributes in XML declaration.
<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>
References: