2016-11-16 80 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