Android changes style dynamically

I describe the properties of my objects (I don’t remember what this object is) in styles.xml. I would like to dynamically change these properties in styles.xml.

Does anyone know how I can do this?

+3
source share
3 answers

I see conflicting answers to this question. It says yes , but it says no . I looked at the android docs for presentation and did not find any setStyle method.

+2
source

You can do this, for example:

In action:

this.setTheme(R.style.ThemeRed);

In styles.xml:

<resources>
  <style name="ThemeBlack" parent="@android:style/Theme">
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:typeface">sans</item>
    <<item name="android:background">#999999</item>
    <item name="android:textSize">16sp</item>
  </style>
  <style name="ThemeRed" parent="@android:style/Theme">
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:typeface">sans</item>
    <item name="android:background">#c81111</item>
    <item name="android:textSize">16sp</item>
  </style>
</resources>
+6
source

styles.xml.

? , ?

, ,

TypedArray a =  context.obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)

(),

  • AttributeSet set = null;, , XML.

  • int[] attrs = R.styleable.MyWidget; , .

  • int defStyleAttr = myWidgetStyle;, , , MyWidget. XML res/values. "myWidgetStyle" , Android .

  • defStyleRes = 0; , .

, , ,

Color  color = a.getColor(R.styleable.MyWidget_background,  R.color.my_default);
a.recycle();

- .

, android a.getColor R.styleable.MyWidget_background. , Android, , , XML MyWidget.

I expect that you can find the correct index by doing a TypedArray search for the required attribute, but that will be inefficient, and TypedArray looks like an unpleasant fixture for a solution. I would use a very long stick to stick it out!

Don

0
source

Source: https://habr.com/ru/post/1750997/


All Articles