从风格上设置指定的视图背景并按主题更改

Set Specified Views background stylistically and changing by themes

我找google一直在搜索关键字,但仍然没有。

我想要的就像:

  <style name="Theme.DefaultWhite" parent="@android:style/Theme.DeviceDefault">
    <item name="android:background">#ffffffff</item>
    <item name="MyCustomBackground">#33ffffff</item>
  </style>
  <style name="Theme.DefaultBlue" parent="@android:style/Theme.DeviceDefault">
    <item name="android:background">#ffffffff</item>
    <item name="MyCustomBackground">#3388ffff</item>
  </style>

并将项目设置为我的指定(其他使用Android默认值)视图。

    <ImageView>
       id = "@+id/NNI_ivCards"
       background="@style/MyCustomBackground"
    </ImageView>
    <ImageView>
       id = "@+id/NNI_ivBarRoot"
    </ImageView>

NNI_ivCards ImageView 必须按主题更改背景颜色,NNI_ivBarRoot不会被主题改变。

我需要风格上的自定义资源,它的价值根据主题而改变。

如果 Android 设计不在样式中放置额外的自定义值,我需要 Java 代码尽可能短。

所以,

此代码可以通过更改主题来更改颜色(任何颜色)。

首先,您必须像这样向 style.xml 添加 2 个样式:

<style name="DefaultTheme" parent="Theme.AppCompat.Light.DarkActionBar">

</style>

<style name="CustomTheme" parent="Theme.DefaultTheme" >

</style>

这里我只是添加了 DefaultThemeCustomTheme,现在转到你的 manifest.xml 并添加这一行 android:theme="@style/DefaultTheme" 到您的 application 标签:

<application
        android:theme="@style/DefaultTheme"
        ...>

创建名为 attrs.xml 的新 xml 文件并添加此代码:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="color1" format="color" />
    <attr name="color2" format="color" />
</resources>

返回样式并添加这些颜色:

<style name="DefaultTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="color1">#FFFFFF</item>
    <item name="color2">#FFFFFF</item>
</style>

<style name="CustomTheme" parent="Theme.DefaultTheme" >
    <item name="color1">#33ffffff</item>
    <item name="color2">#3388ffff</item>
</style>

现在你有 2 个主题,在 DefaultTheme 中,color1 和 color2 是#FFFFFF,在 CustomTheme 中,color1 是#33ffffff,color2 是#3388ffff

转到您的 imageView 并添加此颜色:

<ImageView>
    android:id = "@+id/NNI_ivCards"
    android:background="?attr/color1"
</ImageView>

要更改主题,您必须在 onCreate() 方法中的 setContentView() 方法之前调用 setTheme(R.style.DefaultTheme);,因此您的 activity 应该是这样的:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.CustomTheme);
    setContentView(R.layout.main_activity);
    ....
}