nyconing nyconing - 17 days ago 5
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>
<style name="Theme.DefaultBlue" parent="@android:style/Theme.DeviceDefault">
<item name="android:background">#ffffffff</item>
<item name="MyCustomBackground">#3388ffff</item>
</style>


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

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


NNI_ivCards
ImageView
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

so,

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>

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

</style>

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 :

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

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

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

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>

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

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 :

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

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

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