如何在Android主题声明中添加自定义项?

21

我在styles.xml中有几个自定义主题。
现在每当活动采用这些主题时,它会使用colorPrimarycolorPrimaryDarkcolorAccent的值。
对于我的布局背景,我使用?attr/colorAccent,所以它可以根据所选主题选择背景颜色。
如果我使用上述任何一个值,它都可以正常工作。但我想为我的背景颜色定义一个自定义项目值。
我尝试了下面这个,但它没有起作用。有什么办法让它起作用吗?
我的自定义主题与自定义值:

<style name = "customTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">#4285f4</item>
    <item name="colorPrimaryDark">#2C75F2</item>
    <item name="colorAccent">#E1FFC7</item>
    <item name="customBgColor">#d3d3d3</item>
</style>


我希望你能将它用于页面布局的样式中,就像这样:

<style name="layoutStyle" >
    <item name="android:background">?attr/customBgColor</item>
</style>
1个回答

47
创建一个在图像中显示的attrs.xml文件。
<?xml version="1.0" encoding="utf-8"?>
<resources>

   <!-- Other values-->
   <attr name="customBgColor" format="reference" />

</resources>

输入图片描述

自定义主题1

<style name = "customTheme1" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Other values-->
    <item name="customBgColor">#d3d3d3</item>
</style>

自定义主题2

<style name = "customTheme2" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Other values-->
    <!-- Black Color in theme2-->
    <item name="customBgColor">#111111</item>
</style>

以设置TextView颜色为例。

您可以在任何小部件中的类似方式使用它。

TextView用于下面的活动。

<TextView
    android:id="@+id/txt_rate_us_about"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Rate us on Play Store!"
    android:textColor="?attr/customBgColor"
    android:textSize="20dp" />

想要动态设置主题。

public class AboutUsActivity extends Activity {
    
    int theme = 1;
    // int theme = 2;  2nd theme.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        switch (theme) {
            default:
            case 1:
                this.setTheme(R.style.customTheme1);
                break;
            case 2:
                this.setTheme(R.style.customTheme2);
                break;

        }
        // you must call `setTheme()` before `setContentView()`
        setContentView(R.layout.activity_about);

    }

对于多个活动,您分别为每个活动设置了主题。


我忘记定义属性了,在添加attrs.xml之后,它正常工作了。谢谢@sohail。 - Shree
1
不要将颜色代码放在项目内部,而是将其放在color.xml文件中,并将该颜色标签添加到项目中。 - gayan1991

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接