且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以编程方式创建一个视图后,添加样式

更新时间:2023-11-30 15:52:22

您不能构建一个视图后,应用样式。要做到这一点,正确的方法是使用在Android 5.0以上版本的4个参数的构造函数或创建引用你的风格主题的属性,并使用3-参数构造函数。

You can't apply a style after constructing a view. The correct way to do this is to use the 4-argument constructor on Android 5.0+ or to create a theme attribute that references your style and use the 3-argument constructor.

// Works on versions prior to Android 5.0
RelativeLayout rl = new RelativeLayout(this, null, R.attr.myRelativeLayoutStyle);

// Works on Android 5.0 and above
RelativeLayout r2 = new RelativeLayout(this, null, 0, R.style.MyRelativeLayout);

RES /价值/ attrs.xml:

res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="myRelativeLayoutStyle" format="reference" />
    ...

RES /价值/ styles.xml:

res/values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyRelativeLayout">
        ...
    </style>
    ...

RES /价值/的themes.xml:

res/values/themes.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyAppTheme" parent="...">
        <item name="myRelativeLayoutStyle">@style/MyRelativeLayout</item>
        ...