Add Style after creating a View programmatically

社会主义新天地 提交于 2019-12-01 01:06:48

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/values/attrs.xml:

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

res/values/styles.xml:

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

res/values/themes.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyAppTheme" parent="...">
        <item name="myRelativeLayoutStyle">@style/MyRelativeLayout</item>
        ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!