2016-11-16 84 views
0

我寻找谷歌和保持对搜索关键字的战斗,但仍然没有。设置指定视图背景的风格和主题的变化

我只想要什么样的:

<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_ivCardsImageView必须由主题来改变背景颜色,以及NNI_ivBarRoot将无法​​通过主题改变。

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

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

回答

1

so,

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

首先,你得2样式添加到您的style.xml这样的:

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

</style> 

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

</style> 

这里只是我添加DefaultThemeCustomTheme,现在去你manifest.xml这行android:theme="@style/DefaultTheme"添加到您的应用程序标记:

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

创建新的xml文件attrs.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颜色1和颜色2为#FFFFFF,并在CustomTheme color1是#33ffffff和color2是#3388ffff

转到您的图像查看并添加此颜色:

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

改变你必须调用setTheme(R.style.DefaultTheme);setContentView()方法onCreate()方法的主题,让您的活动应该是这样的:

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

我不能与主题改变它的风格,如果我硬编码视图样式。 – nyconing

+0

所以你需要改变主题的代码,以及随主题变化的颜色。再次看到我的答案来解决它。 –

+0

你是我的英雄!设置?attr/color1做到了!!!!!!那attr可能需要在之下? – nyconing