oligazar
6/21/2017 - 3:43 PM

Custom View

/**
 * Created by Admin on 22/2/18.
 * https://stackoverflow.com/a/29221292/4656400
 */

class PreferenceView: AppCompatButton {

    var value: String? = null
    var subText: String? = null
        set(value) {
            field = value
            text = makeText(title, value)
        }
    var title: String? = null
    var subTextColor: Int = Color.GRAY
    var subTextSize: Float = spToPixels(15f)

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int): super(context, attrs, defStyleAttr) {
        obtainStyledAttributes(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet): super(context, attrs) {
        obtainStyledAttributes(context, attrs)
    }

    private fun obtainStyledAttributes(context: Context, attrs: AttributeSet) {
        val a = context.obtainStyledAttributes(attrs, R.styleable.PreferenceView, 0, 0)
        subTextColor = a.getColor(R.styleable.PreferenceView_subTextColor, subTextColor)
        subTextSize = a.getDimension(R.styleable.PreferenceView_subTextTextSize, subTextSize)
        title = a.getString(R.styleable.PreferenceView_android_text)
        subText = a.getString(R.styleable.PreferenceView_subText)
        text = makeText(title, subText)
        a.recycle()
    }

    private fun makeText(title: CharSequence?, subText: String?): SpannableString {
        val text = title ?: ""
        val fullText = if (subText.isNullOrEmpty()) text else "$text\n$subText"
        val textSpan = SpannableString(fullText)
        if (subText != null) {
            textSpan.setSpan(AbsoluteSizeSpan(subTextSize.toInt()), fullText.length - subText.length, fullText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            textSpan.setSpan(ForegroundColorSpan(subTextColor), fullText.length - subText.length, fullText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        }
        compoundDrawables.mapNotNull { DrawableCompat.wrap(it) }.forEach { DrawableCompat.setTint(it, subTextColor) }  // SRC_IN
        return textSpan
    }
}
// https://antonioleiva.com/kotlin-android-extensions/
generate the constructors with the new intent that uses @JvmOverloads annotation:

Add Android View constructors using '@JvmOverloads'
// use merge tag in conjunction with include tag


    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableLeft="@drawable/ic_book"
        android:drawableStart="@drawable/ic_book"
        android:drawableRight="@drawable/ic_keyboard_arrow_right"
        android:drawableEnd="@drawable/ic_keyboard_arrow_right"
        android:textSize="16sp"
        android:gravity="center_vertical"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:drawablePadding="8dp"
        tools:text="Category name"
        />