如何使自定义视图在Android中继承其父项的样式

问题描述 投票:0回答:1

通过开关,我可以执行此操作:

< 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" />

请注意以下几行:

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

现在,我创建了一个自定义视图以扩展此Switch。我没有进行任何特殊更改:

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)
    }
}

您可以看到,check方法仅是业务逻辑。

为什么我不能使用以前为新类所指的属性?

仅有几篇关于此的文章,但都没有阐明我的要求。

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

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

android android-custom-view android-switch
1个回答
0
投票

Switch不是SwitchCompatSwitchCompat来自AndroidX,因此它使用了应用程序定义的属性。

尝试用app:而不是android:,例如app:switchPadding为有问题的属性添加前缀。

© www.soinside.com 2019 - 2024. All rights reserved.