Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 22  Styles and Themes


Specifying the parent theme in the theme name only works for themes that exist in the same package.
So you will see the Android OS themes use the theme-name inheritance style most of the time, and you
will see the AppCompat library do the same. But once the AppCompat library crosses over to a parent
outside of itself, the explicit parent attribute is used.


In your own applications, it is a good idea to follow the same convention. Specify your theme parent in
the name of your theme if you are inheriting from one of your own themes. If you inherit from a style
or theme in the Android OS, explicitly specify the parent attribute.


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.

Free download pdf