nyconing nyconing - 1 year ago 66
Android Question

Set Specified Views background stylistically and changing by themes

I look for google and keeping fighting on searching keyword. but still nothing.

What I want just like:

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

and set the item at my specified(other of it use android default) Views.

id = "@+id/NNI_ivCards"
id = "@+id/NNI_ivBarRoot"

must be changed the background color by themes, and NNI_ivBarRoot will not changed by themes.

Thanks for reading. Some gift for me?

I need stylistically custom resource which it values changed according to theme.

If it android designed not to put extra custom values in styles,I need java code as short as possible.

Answer Source


this code could change the color (any color) by changing theme.

first, you have to add 2 Style to your style.xml like this:

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


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


here just i add DefaultTheme and CustomTheme, now go to your manifest.xml and add this line android:theme="@style/DefaultTheme" to your application tag :


create new xml file named attrs.xml and add this code :

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

go back to style and add these colors :

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

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

now you have 2 theme, in DefaultTheme color1 and color2 is #FFFFFF, and in CustomTheme color1 is #33ffffff and color2 is #3388ffff

go to your imageView and add this color :

    android:id = "@+id/NNI_ivCards"

to change the theme you must call setTheme(; before setContentView() method in onCreate() method, so your activity should be like this :

protected void onCreate(Bundle savedInstanceState) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download