androidandroid-custom-viewandroid-switch

How to make a custom view inherit it's parent's style in Android


With a Switch I can do this:

< Switch
                android:id="@+id/normal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:gravity="end|center_vertical"
                android:switchPadding="16dp"
                android:thumbTextPadding="16dp"
                android:text="Hello World" />

Pay attention to this lines:

android:switchPadding="16dp"
                    android:thumbTextPadding="16dp"

Now, I made a custom view that extends this Switch. I didn't made any special change:

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.SwitchCompat


class BetterSwitchCompat : SwitchCompat {
    private var listener: OnCheckedChangeListener? = null

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int)
            : super(context, attrs, defStyleAttr)

    override fun setOnCheckedChangeListener(listener: OnCheckedChangeListener?) {
        if (listener != null) {
            this.listener = listener
        }
        super.setOnCheckedChangeListener(listener)
    }

    fun setCheckedSilent(checked: Boolean) {
        toggleListener(false)
        isChecked = checked
        toggleListener(true)
    }

    private fun toggleListener(value: Boolean) {
        if (value) setOnCheckedChangeListener(listener)
        else setOnCheckedChangeListener(null)
    }
}

As you can see, there is nothing more than a business logic for check method.

Why I can't use the attributes I referred to before for the new class?

There are just a few posts about this, but none of them clarify what I am asking.

  1. Android custom view inherit all styles and attributes from parent

  2. How to make a custom view inherit it's parent's style


Solution

  • Switch isn't SwitchCompat. SwitchCompat comes from AndroidX so it uses application-defined attributes.

    Try prefixing the attributes in question with app: instead of android:, such as app:switchPadding.