首页 > 解决方案 > 样式化 android 复合自定义视图

问题描述

请帮助我摆脱精神错乱!

下面的代码可以根据需要设置自定义视图的背景:

public class MyLayout extends LinearLayout {

    public MyLayout(Context context, AttributeSet attrs) {
        super(context, attrs, 0, R.style.MyStyle);
    }

    //Omissions

}

但它给出了:

调用需要 API 级别 21(当前最低为 19):新的 android.widget.LinearLayout

我做了一些手动从样式中提取属性的代码,但它不是动态的 - 因此,如果稍后通过添加属性来更改样式,则必须进行维护。

我已阅读下面的引用,但不太了解与“主题”的交互:

defStyleAttr 当前主题中的一个属性,包含对样式资源的引用,该资源为 StyledAttributes 提供默认值。可以为 0 以不查找默认值。

defStyleRes 为 StyledAttributes 提供默认值的样式资源的资源标识符,仅当 defStyleAttr 为 0 或在主题中找不到时使用。可以为 0 以不查找默认值。

以下不做任何事情:

public class MyLayout extends LinearLayout {

    public MyLayout(Context context, AttributeSet attrs) {
        super(context, attrs, R.style.MyStyle);
    }

    //Omissions

}

我做错了什么?如何简单地使用背景颜色设置自定义组件的样式?

标签: androidandroid-custom-view

解决方案


推荐阅读