Ivan the Russian
Ivan the Russian

Reputation: 110

Editing a style programmaticaly (when the user changes settings)

Note: I'm not looking to SET a style, I want to dynamically change a style which is declared in styles.xml.

For example, my app has a widget with layout like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
    android:id="@+id/widgettext1"
    style="@style/My.WidgetTextView"/>
<TextView
    android:id="@+id/widgettext2"
    style="@style/My.WidgetTextView"/>
<TextView
    android:id="@+id/widgettext3"
    style="@style/My.WidgetTextView"/>
<TextView
    android:id="@+id/widgettext4"
    style="@style/My.WidgetTextView"/>
</LinearLayout>

In styles.xml I have this:

<style name="My.WidgetTextView" parent="android:Widget.TextView">
    <item name="android:background">#99221111</item>
    <item name="android:gravity">center_horizontal|center_vertical</item>
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">25sp</item>
    <item name="android:enabled">true</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:textSize">@dimen/widget_font</item>
</style>

Now, I want to allow user to change some visual settings, like text size or background color.

The easiest way seems to be to edit the style somehow, so I don't have to apply it to each textview or something. Is this possible?

Someone could propose creating a bunch of styles and let the user choose between them, but this is not what I'm looking for.

Upvotes: 1

Views: 65

Answers (1)

Xcihnegn
Xcihnegn

Reputation: 11597

You can set style e.g. My.WidgetTextView programmatically using:

ContextThemeWrapper context = new ContextThemeWrapper(Context, R.style.My.WidgetTextView);

TextView myText = new TextView(context);

However you can not change the attributes of My.WidgetTextView programmatically.

Upvotes: 1

Related Questions