Search code examples
androidandroid-layoutandroid-studioandroid-xmlandroid-theme

how to change a RelativeLayout color based on user preference?


I have an activity that I want to change color based on user preference.

I have created many styles in styles.xml

<style name="Yellow" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">$ffff00</item>
    <item name="colorPrimaryDark">#000000</item>
    <item name="colorAccent">#ffff00</item>
</style>

<style name="Red" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">#ff0000</item>
    <item name="colorPrimaryDark">#000000</item>
    <item name="colorAccent">#ff0000</item>
</style>

It is ok for my toolbar, etc... the problem is that I'd like to change a RelativeLayout background with chosen colorPrimary color. It is getting my default AppTheme color.

oncreate of my activity:

setTheme(R.style.Yellow);

myactivity.xml

  <RelativeLayout
            android:orientation="vertical" android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="@color/colorPrimary">

How can I set myactivity relativelayout bkcolor based on yellow or red color (user will choose one)?


Solution

  • define color in color.xml resources

    <color name="red">#FF0000</color>
    

    and set it to view background

    RelativeLayout rl = (RelativeLayout)findViewById(R.id.rlid);
    rl.setBackgroundColor(R.color.read)
    

    or create color chooser like this

    <item name="colorPrimary">@color/red</item>