覆盖默认的Android主题

时间:2011-01-28 23:14:30

标签: java android

我已经能够覆盖任何名称前缀为“android:”的主题,但Android themes.xml也定义了似乎无法覆盖的属性。例如:

<!-- Variation on the Light theme that turns off the title -->
<style name="Theme.Codebase" parent="android:style/Theme.Light">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="colorBackground">@color/off_white</item>
</style>

colorBackground在Theme.Light xml中定义,但是在这里添加它给了我一个

/res/values/styles.xml:10: error: Error: No resource found that matches the given name: attr 'colorBackground'.

错误。如何覆盖整个应用程序的样式?

2 个答案:

答案 0 :(得分:9)

您可以像修改windowNoTitle这样的属性一样覆盖标准属性,只是不要忘记添加android:前缀,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="SEclubTheme" parent="@android:style/Theme">
        <item name="android:colorForeground">@color/bright_foreground_dark</item>
        <item name="android:colorBackground">@color/background_dark</item>
    </style>
</resources>

答案 1 :(得分:3)

如果没有attr前缀,colorBackground将成为您需要定义的属性。请考虑以下示例theme_dependent_icon中定义styles.xml

<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <declare-styleable name="custom_menu">
            <attr name="theme_dependent_icon" format="reference"/>
    </declare-styleable>
    <style name="MyDarkTheme" parent="android:Theme" >
        <item name="theme_dependent_icon">@drawable/ic_search_dark</item>
    </style>
    <style name="MyLightTheme" parent="android:Theme.Light" >
        <item name="theme_dependent_icon">@drawable/ic_search_light</item>
    </style>
</resources>

然后,您可以在?attr/theme_dependent_icon

中通过main_activity.xml使用该属性
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="?attr/theme_dependent_icon" />
</LinearLayout>

在此示例中,由于我使用了自定义主题名称MyDarkThemeMyLightTheme,因此需要在onCreate之前的主要活动的setContentView期间选择它们,即< / p>

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.MyDarkTheme); // causes ic_search_dark.png to be shown
    // setTheme(R.style.MyLightTheme); // causes ic_search_light.png to be shown
    setContentView(R.layout.main_activity);
}

调用setTheme()是在运行时选择主题的一种方法。另一种方法是在styles.xmlvaluesvalues-11对应默认主题,主题为Android 3.0(API-11)和{3}}下的资源中定义values-14的多个版本。适用于Android 4.0的主题(API-14)。