For the More Curious: Accessing Theme Attributes

Once attributes are declared in your theme, you can access them in XML or in code.

To access a theme attribute in XML, you use the notation that you saw on the listSeparatorTextViewStyle attribute in Chapter 7. When referencing a concrete value in XML, such as a color, you use the @ notation. @color/gray points to a specific resource.

When referencing a resource in the theme, you use the ? notation:

<Button xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list_item_sound_button"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:background="?attr/colorAccent"
    tools:text="Sound name"/>

The ? notation says to use the resource that the colorAccent attribute on your theme points to. In your case, this would be the gray color that you defined in your colors.xml file.

You can also use theme attributes in code, although it is much more verbose.

Resources.Theme theme = getActivity().getTheme();
int[] attrsToFetch = { R.attr.colorAccent };
TypedArray a = theme.obtainStyledAttributes(R.style.AppTheme, attrsToFetch);
int accentColor = a.getInt(0, 0);
a.recycle();

On the Theme object, you ask to resolve the attribute R.attr.colorAccent that is defined in your AppTheme: R.style.AppTheme. This call returns a TypedArray, which holds your data. On the TypedArray, you ask for an int value to pull out the accent color. From here, you can use that color to change the background of a button, for example.

The toolbar and buttons in BeatBox are doing exactly this to style themselves based on your theme attributes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.208.72