Friday, September 20, 2013

Android: Set Custom Attributes Via Programmatically and XML



Resources.Theme holds the current attribute values for a particular theme. In other words, a Theme is a set of values for resource attributes; these are used in conjunction with TypedArray to resolve the final value for an attribute.
The Theme's attributes come into play in two ways:
1.      A styled attribute can explicit reference a value in the theme through the "?themeAttribute" syntax;
2.      If no value has been defined for a particular styled attribute, as a last resort we will try to find that attribute's value in the Theme.
Let us take first point, where we need to get the value of a custom attribute programmatically.
We can access custom attr programmatically with the help of Resources.Theme class.

TypedValue, Container for a dynamically typed data value.
resolveAttribute, Retrieve the value of an attribute in the Theme.

Example:
Create two TextView in main.xml file, where we are changing background of TextView using custom attribute via xml and programmatically.

Define your own custom attribute: Create attr.xml in your layout folder
xml version="1.0" encoding="UTF-8"?>
<resources>

    <attr name="CustomYellowColor" format="reference|color" />
    <attr name="CustomBlueColor" format="reference|color" />

</resources>

Change Style.xml file
<style name="AppTheme" parent="AppBaseTheme">
    <item name="CustomYellowColor">@color/yellow</item>
    <item name="CustomBlueColor">@color/blue</item>
</style>

<color name="yellow">#FFFF00</color>
<color name="blue">#0040FF</color>

Go to your main.xml and change background color of a TextView’s

XML:
<TextView
   android:id="@+id/textView2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="?attr/CustomBlueColor"
   android:text="@string/xml" />

Programmatically:

TextView prgmTV = (TextView) findViewById(R.id.textView1);
Resources.Theme themes = getTheme();
TypedValue storedValueInTheme = new TypedValue();
if (themes.resolveAttribute(R.attr.CustomYellowColor, storedValueInTheme, true)) {
            prgmTV.setBackgroundColor(storedValueInTheme.data);
}


Output:

3 comments :

  1. Change Style.xml file



    What if in above code instead of direct writing color we want to provide style for attribute values.
    How to do that

    ReplyDelete