【问题标题】:Android, how to define a defaut style for a custom ViewAndroid,如何为自定义视图定义默认样式
【发布时间】:2021-06-12 12:57:50
【问题描述】:

我的自定义视图类:

class SearchBox : FrameLayout {

    constructor(context: Context) : super(context)

    constructor(
        context: Context,
        attrs: AttributeSet?
    ) : this(context, attrs, R.attr.searchBoxStyle)

    constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        R.style.SearchBoxStyle
    )

    constructor(
        context: Context,
        attrs: AttributeSet?,
        @AttrRes defStyleAttr: Int,
        @StyleRes defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {

        inflate(context, R.layout.search_box, this)

        val a = context.obtainStyledAttributes(attrs, R.styleable.SearchBox, defStyleAttr, defStyleRes)

        a.recycle()
    }
}

样式声明:

<style name="SearchBoxStyle" parent="">
    <item name="background">@color/black</item>
</style>

Styleable(暂时为空,我会使用平台属性,例如“背景”):

<declare-styleable name="SearchBox">
</declare-styleable>

问题 永远不会设置“背景”属性。

如何为自定义视图定义简单的默认样式?

更新

    <declare-styleable name="SearchBox">
        <attr name="background" format="reference" />
    </declare-styleable>
constructor(
        context: Context,
        attrs: AttributeSet?,
        @AttrRes defStyleAttr: Int,
        @StyleRes defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {

        inflate(context, R.layout.search_box, this)

        val a = context.obtainStyledAttributes(attrs, R.styleable.SearchBox, defStyleAttr, defStyleRes)
        val background = a.getDrawable(R.styleable.SearchBox_background)
        background?.apply { setBackground(this) }

        a.recycle()
    }

这是正确的方法吗?

我希望有一种方法可以做到,即使不重新定义平台的所有属性然后手动应用它们。

【问题讨论】:

    标签: android styles android-custom-view


    【解决方案1】:

    我自己回答,平台属性有效,但它们以“android:...”开头。

    所以,使用"android:background" 就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      相关资源
      最近更新 更多