【问题标题】:Custom CheckBox with default style具有默认样式的自定义复选框
【发布时间】:2020-05-28 09:07:27
【问题描述】:

我需要创建一个具有默认材质样式的自定义 CheckBox。

我的班级是这样定义的

class CustomCheckBox @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : CheckBox(context, attrs, defStyleAttr) {

}

如果我查看默认 CheckBox 的属性,它们定义了以下属性

background: @android:drawable/control_background_40pd_material
button: @android:drawable/btn_check_material_anim

但派生的小部件没有它们。

如何将这些应用到派生类?

更新

我尝试扩展MaterialCheckBox,默认属性现在显示在面板中,但它给出了一个例外

IllegalArgumentException: The style on this component requires your app 
theme to be Theme.MaterialComponents (or a descendant)

我没有使用Material 主题,那么如何将默认背景和可绘制按钮应用于自定义类?

【问题讨论】:

  • 您是否尝试从 AppCompatCheckbox 或材质库中的复选框进行扩展?
  • 我提到的默认 CheckBox 在布局中定义为<CheckBox/>。我也尝试过扩展AppCompatCheckboxMaterialCheckBox,但没有任何改变。
  • 我刚刚尝试清理项目并再次从MaterialCheckBox 扩展,现在它确实设置了默认属性,但现在它显示错误。请参阅问题中的 Udate

标签: android kotlin checkbox material-design android-custom-view


【解决方案1】:

事实证明@JvmOverloadsthis post 中描述的问题的根源

我把它换成了

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

现在它按预期工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2015-12-29
    相关资源
    最近更新 更多