1

I am new to android development and currently making a calculator app. In it, my activity has number of buttons on which I apply the same style. The structure of code is something like as below

layout.xml <LinearLayout> <Button android:text="Button 1" style="@style/styleName" > <Button android:text="Button 2" style="@style/styleName" > <Button android:text="Button 3" style="@style/styleName" > </LinearLayout> style.xml

<resources> <style name="styleName"> <item name="attribute1">attribute1Value</item> <item name="attribute2">attribute2Value</item> <item name="attribute3">attribute3Value</item> <item name="android:background">BackgroundValue</item> </style> </resources>

Now I want to provide a feature to user in which when he/she selects a particular theme from the setting, the background of all buttons will change. This can be achieved if I can change the value of background color in styleName. I am not sure how to achieve this. I look around the web and didn't find any satisfying answer for achieving the same.

Vijay
  • 439
  • 3
  • 15
  • http://stackoverflow.com/questions/13719103/how-to-retrieve-style-attributes-programatically-from-styles-xml Did you try this? – Amsheer Apr 07 '15 at 11:16
  • The above link is for getting the value but the requirement is for changing the value. – Subho Mar 15 '19 at 10:37

2 Answers2

0

Apparently, you cannot change style programmatically.if i were you, i would create many selector.xml in /res/drawable/ like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:state_pressed="true"
    android:drawable="@drawable/light_btn_pressed" />
   <item
    android:state_pressed="false"
    android:drawable="@drawable/light_btn_normal" />
</selector>

For each "style" you will have a selector (light,dark,..etc). Insert in drawable your colors or images. After these, you can apply these selectors by setting android:background="@drawable/my_button". Additional, with this method you will achieve also the interaction on button states.

I hope it helps

-1

You can have access the attributes of style xml through Typed array. suppose you have a customstyle xml.

 int[] attrs ={android.R.attr.textColor, android.R.attr.background,android.R.attr.text};
TypedArray array = obtainStyledAttributes(R.style.CustomStyle, attrs);

// Fetching the colors defined in your style
int textColor = array.getColor(0, Color.BLACK);
int backgroundColor = array.getColor(1, Color.BLACK);