Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Android 7: Resources Kirk Scott 1 2 3 • This is a “light” unit, which just tries to consolidate some things before moving on to more complicated topics • Resources came up in the very first examples • This unit expands on that initial introduction • However, it doesn’t treat this topic in complete detail or in depth 4 • My theory on a lot of programming is that you only really learn things when you need them for a program you’re developing • Hopefully, you get just enough background on this topic here so that you can go further with it later on if you want to 5 • This is a list of the sections in this set of overheads: • 7.1 Introduction • 7.2 Strings • 7.3 String Arrays • 7.4 More Resource Types • 7.5 IDs 6 • • • • • • • 7.6 Integers 7.7 Dimensions 7.8 Colors 7.9 Styles 7.10 Layouts 7.11 Menus 7.12 Graphics (Drawables) 7 • • • • • • • • 7.13 7.14 7.15 7.16 7.17 7.18 7.19 7.20 Typed Arrays (of Drawables) Animations XML Files Raw Files Errors Designing an App Using the Graphical Development Tools Example App with Resources 8 7.1 Introduction 9 • The fundamental idea behind resources was introduced earlier: • Code should consist only of executable logic • Store everything else separately from it, in XML files • In the Android environment, there is a predefined directory structure for storing resources 10 • A screenshot of the environment is given on the following overhead for MyEchoApp • It shows the explorer on the left with selected subdirectories of the res (resources) directory expanded • All of the directories and files shown are the defaults that come with any app 11 12 • In essence, large parts of this unit are an introduction to the information you can find in the developer tutorials • I won’t cover all of the resource types • Instead, I’ll select some of them and run through the tutorial information on that selected subset • The table on the following overhead summarizes the selected subset of resource types 13 Resource Type Required Directory Suggested File Names XML Tag Strings /res/values strings.xml <string> IDs /res/values filename.xml (any file) <item> Integers /res/values integers.xml <integer> Dimensions /res/values dimens.xml <dimen> Colors /res/values colors.xml <color> Styles /res/values styles.xml <style> Layouts /res/layout e.g., activity_main.xml Various layout tags Menus /res/menu e.g., mainmenu.xml <menu> Graphics /res/drawable e.g., icon.png, logo.png Supported graphics files or drawable definition XML files such as shapes Animations /res/animator e.g., fadesequence.xml, spinsequenc.xml <set>, <alpha>, <scale>, <translate>, <rotate> XML Files /res/xml e.g., data.xml No defined tag Raw Files /res/raw e.g., jingle.mp3 No defined tag 14 7.2 Strings • We already know about strings • However, mostly what we know consists of copy and paste • The point now is to actually read the information about string resources • The information from the tutorials starts on the following overhead 15 • String Resources • A string resource provides text strings for your application with optional text styling and formatting. • There are three types of resources that can provide your application with strings: • String XML resource that provides a single string. 16 • String Array XML resource that provides an array of strings. • Quantity Strings (Plurals) XML resource that carries different strings for pluralization. • All strings are capable of applying some styling markup and formatting arguments. • For information about styling and formatting strings, see the section about Formatting and Styling. • [Note that these last two types of resources are not covered in these overheads.] 17 • String • A single string that can be referenced from the application or from other resource files (such as an XML layout). • Note: A string is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). • So, you can combine string resources with other simple resources in the one XML file, under one <resources> element. 18 • file location: • res/values/filename.xml The filename is arbitrary. The <string> element's name will be used as the resource ID. • compiled resource datatype: • Resource pointer to a String. • resource reference: • In Java: R.string.string_name • In XML:@string/string_name 19 • syntax: • <?xml version="1.0" encoding="utf-8"?> <resources> <string name="string_name" >text_string</string> </resources> 20 • • • • • • • • • elements: <resources> Required. This must be the root node. No attributes. <string> A string, which can include styling tags. Beware that you must escape apostrophes and quotation marks. For more information about how to properly style and format your strings see Formatting and Styling, below. • attributes: • name String. A name for the string. This name will be used as the resource ID. 21 • example: • XML file saved at res/values/strings.xml: • <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello!</string> </resources> 22 • This layout XML applies a string to a View: • <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> 23 • This application code retrieves a string: • String string = getString(R.string.hello); • You can use either getString(int) or getText(int) to retrieve a string. • getText(int) will retain any rich text styling applied to the string. 24 7.3 String Arrays • String Array • An array of strings that can be referenced from the application. • Note: A string array is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). • As such, you can combine string array resources with other simple resources in the one XML file, under one <resources> element. 25 • • • • • • • • file location: res/values/filename.xml The filename is arbitrary. The <string-array> element's name will be used as the resource ID. compiled resource datatype: Resource pointer to an array of Strings. resource reference: In Java: R.array.string_array_name 26 • syntax: • <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="string_array_name"> <item >text_string</item> </string-array> </resources> 27 • • • • • • • • • • • • elements: <resources> Required. This must be the root node. No attributes. <string-array> Defines an array of strings. Contains one or more <item> elements. attributes: name String. A name for the array. This name will be used as the resource ID to reference the array. 28 • <item> • A string, which can include styling tags. • The value can be a reference to another string resource. • Must be a child of a <string-array> element. • Beware that you must escape apostrophes and quotation marks. • See Formatting and Styling, below, for information about to properly style and format your strings. • No attributes. 29 • example: • XML file saved at res/values/strings.xml: • <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="planets_array"> <item>Mercury</item> <item>Venus</item> <item>Earth</item> <item>Mars</item> </string-array> </resources> 30 • This application code retrieves a string array: • Resources res = getResources(); String[] planets = res.getStringArray(R.array.planets_array); 31 7.4 More Resource Types • The tutorials have a catch-all group of resource types which include the four next types that will be covered in these overheads • For reference purposes, the whole set is listed on the following overheads before launching into the individual ones that have been chosen for detailed presentation 32 • More Resource Types • This page defines more types of resources you can externalize, including: • Bool XML resource that carries a boolean value. • Color XML resource that carries a color value (a hexadecimal color). • Dimension XML resource that carries a dimension value (with a unit of measure). 33 • ID XML resource that provides a unique identifier for application resources and components. • Integer XML resource that carries an integer value. • Integer Array XML resource that provides an array of integers. • Typed Array XML resource that provides a TypedArray (which you can use for an array of drawables). 34 • [The Typed Array resource type will be covered right after the drawable resource type • Drawing images may be one of the first things developers might want to add to their apps • Therefore, it seems worthwhile to see how to deal with sets of images] 35 7.5 IDs • Out of the previous list of resource types, IDs are covered first since they are also things we’ve seen before • Just like with Strings, the main thing to notice is that we just mindlessly copied and pasted up to this point • Now is the time to read and see what’s actually going on 36 • In particular, remember the use of the “+” sign in the syntax of the examples so far • The activity_main.xml layout file for MyEchoApp contained this line of code, for example: • android:id="@+id/edit_message" /> • This was a shortcut, where an id could be defined where needed in the layout 37 • The following overheads from the tutorials give the whole ball of wax on IDs • They describe everything there is to know about them beyond the shortcut 38 • ID • A unique resource ID defined in XML. • Using the name you provide in the <item> element, the Android developer tools create a unique integer in your project's R.java class, which you can use as an identifier for an application resources (for example, a View in your UI layout) or a unique integer for use in your application code (for example, as an ID for a dialog or a result code). 39 • Note: An ID is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). • As such, you can combine ID resources with other simple resources in the one XML file, under one <resources> element. • Also, remember that an ID resources does not reference an actual resource item; • it is simply a unique ID that you can attach to other resources or use as a unique integer in your application. 40 • file location: • res/values/filename.xml The filename is arbitrary. • resource reference: • In Java: R.id.name • In XML: @[package:]id/name 41 • syntax: • <?xml version="1.0" encoding="utf-8"?> <resources> <item type="id" name="id_name" /> </resources> 42 • • • • • • • • • • • • elements: <resources> Required. This must be the root node. No attributes. <item> Defines a unique ID. Takes no value, only attributes. attributes: type Must be "id". name String. A unique name for the ID. 43 • example: • XML file saved at res/values/ids.xml: • <?xml version="1.0" encoding="utf-8"?> <resources> <item type="id" name="button_ok" /> <item type="id" name="dialog_exit" /> </resources> 44 • Then, this layout snippet uses the "button_ok" ID for a Button widget: • <Button android:id="@id/button_ok" style="@style/button_style" /> 45 • Notice that the android:id value does not include the plus sign in the ID reference, because the ID already exists, as defined in the ids.xml example above. • (When you specify an ID to an XML resource using the plus sign—in the format android:id="@+id/name"—it means that the "name" ID does not exist and should be created.) 46 • [The last example in the subsection on IDs in the tutorials isn’t very helpful, so it is not included.] 47 7.6 Integers • Integer • An integer defined in XML. • Note: An integer is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). • As such, you can combine integer resources with other simple resources in the one XML file, under one <resources> element. 48 • • • • file location: res/values/filename.xml The filename is arbitrary. The <integer> element's name will be used as the resource ID. • resource reference: • In Java: R.integer.integer_name In XML: @[package:]integer/integer_name 49 • syntax: • <?xml version="1.0" encoding="utf-8"?> <resources> <integer name="integer_name" >integer</integer> </resources> 50 • • • • • • • • • • elements: <resources> Required. This must be the root node. No attributes. <integer> An integer. attributes: name String. A name for the integer. This will be used as the resource ID. 51 • example: • XML file saved at res/values/integers.xml: • <?xml version="1.0" encoding="utf-8"?> <resources> <integer name="max_speed">75</integer> <integer name="min_speed">5</integer> </resources> 52 • This application code retrieves an integer: • Resources res = getResources(); • int maxSpeed = res.getInteger(R.integer.max_speed); 53 • This application code retrieves an integer: • Resources res = getResources(); int maxSpeed = res.getInteger(R.integer.max_speed); 54 7.7 Dimensions • Dimension • A dimension value defined in XML. • A dimension is specified with a number followed by a unit of measure. • For example: 10px, 2in, 5sp. • The following units of measure are supported by Android: 55 • dp • Density-independent Pixels - An abstract unit that is based on the physical density of the screen. • These units are relative to a 160 dpi (dots per inch) screen, on which 1dp is roughly equal to 1px. • When running on a higher density screen, the number of pixels used to draw 1dp is scaled up by a factor appropriate for the screen's dpi. • Likewise, when on a lower density screen, the number of pixels used for 1dp is scaled down. 56 • The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. • Using dp units (instead of px units) is a simple solution to making the view dimensions in your layout resize properly for different screen densities. • In other words, it provides consistency for the real-world sizes of your UI elements across different devices. 57 • sp • Scale-independent Pixels - This is like the dp unit, but it is also scaled by the user's font size preference. • It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user's preference. 58 • pt • Points - 1/72 of an inch based on the physical size of the screen. • px Pixels - Corresponds to actual pixels on the screen. • This unit of measure is not recommended because the actual representation can vary across devices; • each devices may have a different number of pixels per inch and may have more or fewer total pixels available on the screen. 59 • mm • Millimeters - Based on the physical size of the screen. • in • Inches - Based on the physical size of the screen. 60 • Note: • A dimension is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). • As such, you can combine dimension resources with other simple resources in the one XML file, under one <resources> element. 61 • • • • file location: res/values/filename.xml The filename is arbitrary. The <dimen> element's name will be used as the resource ID. • resource reference: • In Java: R.dimen.dimension_name In XML: @[package:]dimen/dimension_name 62 • syntax: • <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="dimension_name" >dimension</dimen> </resources> 63 • • • • • • elements: <resources> Required. This must be the root node. No attributes. <dimen> A dimension, represented by a float, followed by a unit of measurement (dp, sp, pt, px, mm, in), as described above. • attributes: • name String. • A name for the dimension. This will be used as the resource ID. 64 • example: • XML file saved at res/values/dimens.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="textview_height">25dp</dimen> <dimen name="textview_width">150dp</dimen> <dimen name="ball_radius">30dp</dimen> <dimen name="font_size">16sp</dimen> </resources> 65 • This application code retrieves a dimension: • Resources res = getResources(); float fontSize = res.getDimension(R.dimen.font_size); 66 • This layout XML applies dimensions to attributes: • <TextView android:layout_height="@dimen/textview_height" android:layout_width="@dimen/textview_width" android:textSize="@dimen/font_size"/> 67 7.8 Colors • Color • A color value defined in XML. • The color is specified with an RGB value and alpha channel. • You can use a color resource any place that accepts a hexadecimal color value. • You can also use a color resource when a drawable resource is expected in XML (for example, android:drawable="@color/green"). 68 • The value always begins with a pound (#) character and then followed by the Alpha-RedGreen-Blue information in one of the following formats: • #RGB • #ARGB • #RRGGBB • #AARRGGBB • [The alpha channel is a measure of transparency] 69 • Note: • A color is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). • As such, you can combine color resources with other simple resources in the one XML file, under one <resources> element. 70 • • • • file location: res/values/colors.xml The filename is arbitrary. The <color> element's name will be used as the resource ID. • resource reference: • In Java: R.color.color_name In XML: @[package:]color/color_name 71 • syntax: • <?xml version="1.0" encoding="utf-8"?> <resources> <color name="color_name" >hex_color</color> </resources> 72 • • • • • • • • • • elements: <resources> Required. This must be the root node. No attributes. <color> A color expressed in hexadecimal, as described above. attributes: name String. A name for the color. This will be used as the resource ID. 73 • example: • XML file saved at res/values/colors.xml: • <?xml version="1.0" encoding="utf-8"?> <resources> <color name="opaque_red">#f00</color> <color name="translucent_red">#80ff0000</color> </resources> 74 • This application code retrieves the color resource: • Resources res = getResources(); int color = res.getColor(R.color.opaque_red); 75 • This layout XML applies the color to an attribute: • <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="@color/translucent_red" android:text="Hello"/> 76 7.9 Styles • Style Resource • A style resource defines the format and look for a UI. • A style can be applied to an individual View (from within a layout file) or to an entire Activity or application (from within the manifest file). • For more information about creating and applying styles, please read Styles and Themes. 77 • Note: • A style is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). • As such, you can combine style resources with other simple resources in the one XML file, under one <resources> element. 78 • • • • file location: res/values/filename.xml The filename is arbitrary. The element's name will be used as the resource ID. • resource reference: • In XML: @[package:]style/style_name 79 • syntax: • <?xml version="1.0" encoding="utf-8"?> <resources> <style name="style_name" parent="@[package:]style/style_to_inherit"> <item name="[package:]style_property_name" >style_value</item> </style> </resources> 80 • • • • • elements: <resources> Required. This must be the root node. No attributes. 81 • • • • • • <style> Defines a single style. Contains <item> elements. attributes: name String. Required. A name for the style, which is used as the resource ID to apply the style to a View, Activity, or application. • parent Style resource. • Reference to a style from which this style should inherit style properties. 82 • • • • • • • <item> Defines a single property for the style. Must be a child of a <style> element. attributes: name Attribute resource. Required. The name of the style property to be defined, with a package prefix if necessary (for example android:textColor). 83 • example: • • XML file for the style (saved in res/values/): <?xml version="1.0" encoding="utf-8"?> <resources> <style name="CustomText" parent="@style/Text"> <item name="android:textSize">20sp</item> <item name="android:textColor">#008</item> </style> </resources> 84 • XML file that applies the style to a TextView (saved in res/layout/): • <?xml version="1.0" encoding="utf-8"?> <EditText style="@style/CustomText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello, World!" /> 85 7.10 Layouts • [Layouts are included in this list because they are resources. • Only the preliminary part of the documentation in the tutorials will be given here. • A discussion of layouts and their use is the topic of the next set of overheads.] 86 • Layout Resource • A layout resource defines the architecture for the UI in an Activity or a component of a UI. 87 • • • • • file location: res/layout/filename.xml The filename will be used as the resource ID. compiled resource datatype: Resource pointer to a View (or subclass) resource. • resource reference: • In Java: R.layout.filename • In XML: @[package:]layout/filename 88 • syntax: • <?xml version="1.0" encoding="utf-8"?> <ViewGroup xmlns:android="http://schemas.android.com/apk/res/android" android:id="@[+][package:]id/resource_name" android:layout_height=["dimension" | "fill_parent" | "wrap_content"] android:layout_width=["dimension" | "fill_parent" | "wrap_content"] [ViewGroup-specific attributes] > <View android:id="@[+][package:]id/resource_name" android:layout_height=["dimension" | "fill_parent" | "wrap_content"] android:layout_width=["dimension" | "fill_parent" | "wrap_content"] [View-specific attributes] > <requestFocus/> </View> <ViewGroup > <View /> </ViewGroup> <include layout="@layout/layout_resource"/> </ViewGroup> 89 • Note: The root element can be either a ViewGroup, a View, or a <merge> element, but there must be only one root element and it must contain the xmlns:android attribute with the android namespace as shown. 90 7.11 Menus • [Menus are included in this list because they are resources. • Only the preliminary part of the documentation in the tutorials will be given here. • A discussion of menus and their use will be included in a future set of overheads.] 91 • Menu Resource • A menu resource defines an application menu (Options Menu, Context Menu, or submenu) that can be inflated with MenuInflater. • For a guide to using menus, see the Menus developer guide. 92 • • • • • file location: res/menu/filename.xml The filename will be used as the resource ID. compiled resource datatype: Resource pointer to a Menu (or subclass) resource. • resource reference: • In Java: R.menu.filename • In XML: @[package:]menu.filename 93 • syntax: • <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@[+][package:]id/resource_name" android:title="string" android:titleCondensed="string" android:icon="@[package:]drawable/drawable_resource_name" android:onClick="method name" android:showAsAction=["ifRoom" | "never" | "withText" | "always" | "collapseActionView"] android:actionLayout="@[package:]layout/layout_resource_name" android:actionViewClass="class name" android:actionProviderClass="class name" android:alphabeticShortcut="string" android:numericShortcut="string" android:checkable=["true" | "false"] android:visible=["true" | "false"] android:enabled=["true" | "false"] android:menuCategory=["container" | "system" | "secondary" | "alternative"] android:orderInCategory="integer" /> 94 • <group android:id="@[+][package:]id/resource name" android:checkableBehavior=["none" | "all" | "single"] android:visible=["true" | "false"] android:enabled=["true" | "false"] android:menuCategory=["container" | "system" | "secondary" | "alternative"] android:orderInCategory="integer" > <item /> </group> <item > <menu> <item /> </menu> </item> </menu> 95 7.12 Graphics (Drawables) • [Note: • As you will soon see there are lots of different drawable types • This set of overheads will show the preview list of all drawable types but only show the full documentation for bitmaps • In the long run, nine-patch graphics are more flexible • If you want to use nine-patch graphics or anything fancier, it will be up to you to figure out how.] 96 • Drawable Resources • A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon. 97 • • • • • • There are several different types of drawables: Bitmap File A bitmap graphic file (.png, .jpg, or .gif). Creates a BitmapDrawable. Nine-Patch File A PNG file with stretchable regions to allow image resizing based on content (.9.png). • Creates a NinePatchDrawable. 98 • Layer List • A Drawable that manages an array of other Drawables. • These are drawn in array order, so the element with the largest index is be drawn on top. • Creates a LayerDrawable. • State List • An XML file that references different bitmap graphics for different states (for example, to use a different image when a button is pressed). • Creates a StateListDrawable. 99 • Level List • An XML file that defines a drawable that manages a number of alternate Drawables, each assigned a maximum numerical value. • Creates a LevelListDrawable. • Transition Drawable • An XML file that defines a drawable that can cross-fade between two drawable resources. • Creates a TransitionDrawable. 100 • Inset Drawable • An XML file that defines a drawable that insets another drawable by a specified distance. • This is useful when a View needs a background drawble that is smaller than the View's actual bounds. • Clip Drawable • An XML file that defines a drawable that clips another Drawable based on this Drawable's current level value. • Creates a ClipDrawable. 101 • Scale Drawable • An XML file that defines a drawable that changes the size of another Drawable based on its current level value. • Creates a ScaleDrawable • Shape Drawable • An XML file that defines a geometric shape, including colors and gradients. • Creates a ShapeDrawable. 102 • Also see the Animation Resource document for how to create an AnimationDrawable. • Note: • A color resource can also be used as a drawable in XML. • For example, when creating a state list drawable, you can reference a color resource for the android:drawable attribute (android:drawable="@color/green"). 103 • Bitmap • A bitmap image. • Android supports bitmap files in a three formats: .png (preferred), .jpg (acceptable), .gif (discouraged). • You can reference a bitmap file directly, using the filename as the resource ID, or create an alias resource ID in XML. 104 A One-Overhead Wikipedia Interlude, FYI • Portable Network Graphics • From Wikipedia, the free encyclopedia • Portable Network Graphics (PNG /ˈpɪŋ/[2] PING) is a raster graphics file format that supports lossless data compression. PNG was created as an improved, non-patented replacement for Graphics Interchange Format (GIF), and is the most used lossless image compression format on the World Wide Web.[3] 105 • Note: Bitmap files may be automatically optimized with lossless image compression by the aapt tool during the build process. For example, a true-color PNG that does not require more than 256 colors may be converted to an 8-bit PNG with a color palette. This will result in an image of equal quality but which requires less memory. So be aware that the image binaries placed in this directory can change during the build. If you plan on reading an image as a bit stream in order to convert it to a bitmap, put your images in the res/raw/ folder instead, where they will not be optimized. 106 • Bitmap File • A bitmap file is a .png, .jpg, or .gif file. • Android creates a Drawable resource for any of these files when you save them in the res/drawable/ directory. 107 • • • • • • • • file location: res/drawable/filename.png (.png, .jpg, or .gif) The filename is used as the resource ID. compiled resource datatype: Resource pointer to a BitmapDrawable. resource reference: In Java: R.drawable.filename In XML: @[package:]drawable/filename 108 • example: • With an image saved at res/drawable/myimage.png, this layout XML applies the image to a View: • <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/myimage" /> 109 • The following application code retrieves the image as a Drawable: • Resources res = getResources(); Drawable drawable = res.getDrawable(R.drawable.myimage); 110 • see also: 2D Graphics • BitmapDrawable 111 Commentary on Drawables • Everything listed above is “apparently” true • This comment dwells on the fact that even though I did the things as shown, I had problems • I got it to work only after slogging through a succession of inexplicable error messages in the layout file that used the drawable— • And the additional errors that resulted from the fact that the R.java file wasn’t created 112 Commentary cont’d. • • • • This was the setup: I had a png file saved as a resource This was its full path name: res/drawable-hdpi/sleepy2.png 113 Commentary cont’d. • This was the corresponding part of the layout file which used the drawable resource: • <ImageView android:layout_width="wrap_content" • android:layout_height="0dp" android:layout_weight="1" • android:layout_gravity="center_horizontal" • android:src="@drawable/sleepy2" /> 114 Commentary cont’d. • Notice 3 things in particular about how the resource is identified in this line of XML: • android:src="@drawable/sleepy2" • The name does not include res • The name includes drawable, not drawable-hdpi • The name does not include the file extension, .png 115 Commentary cont’d. • Even though I thought I had it right, I got this error message on the XML file: • “No resource found that matches the given name.” • Eventually, by black magic, it did work, but not before encountering something else 116 Commentary cont’d. • If you search the Web for this error message you will be directed to places like stackoverflow.com • There, you will find this suggestion: • Put a plus sign into the android:src line in the XML, like this: • android:src="@+drawable/sleepy2" • Warning, not recommended. Read further. 117 Commentary cont’d. • It looks harmless enough • It looks like the shortcut syntax for giving an id to a resource • It may even be the solution to some problems some times • However, I found it insidious 118 Commentary cont’d. • The compiler wouldn’t complain about it • An R.java file would be created • And at run time there would be cryptic errors that referred back to a problem in the XML file: 119 Commentary cont’d. • • • • • • • FATAL EXCEPTION: main Java.lang.RuntimeException: Unable to start activity ComponentInfo{ nameOfYourActivity}: android.view.InflateException: Binary XML file line n: Error inflating class <unknown> 120 Commentary cont’d. • This runtime error went away when I got rid of the plus sign in the XML 121 7.13 Typed Arrays (of Drawables) • Typed Array • A TypedArray defined in XML. • You can use this to create an array of other resources, such as drawables. 122 • Note that the array is not required to be homogeneous, so you can create an array of mixed resource types, but you must be aware of what and where the data types are in the array so that you can properly obtain each item with the TypedArray's get...() methods. 123 • Note: • A typed array is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). • As such, you can combine typed array resources with other simple resources in the one XML file, under one <resources> element. 124 • • • • file location: res/values/filename.xml The filename is arbitrary. The <array> element's name will be used as the resource ID. 125 • • • • compiled resource datatype: Resource pointer to a TypedArray. resource reference: In Java: R.array.array_name In XML: @[package:]array.array_name 126 • syntax: • <?xml version="1.0" encoding="utf-8"?> <resources> <array name="integer_array_name"> <item>resource</item> </array> </resources> 127 • • • • • elements: <resources> Required. This must be the root node. No attributes. 128 • • • • • • • <array> Defines an array. Contains one or more child <item> elements. attributes: android:name String. A name for the array. This name will be used as the resource ID to reference the array. 129 • <item> • A generic resource. • The value can be a reference to a resource or a simple data type. • Must be a child of an <array> element. • No attributes. 130 • example: XML file saved at res/values/arrays.xml: 131 • <?xml version="1.0" encoding="utf-8"?> <resources> <array name="icons"> <item>@drawable/home</item> <item>@drawable/settings</item> <item>@drawable/logout</item> </array> <array name="colors"> <item>#FFFF0000</item> <item>#FF00FF00</item> <item>#FF0000FF</item> </array> </resources> 132 • This application code retrieves each array and then obtains the first entry in each array: 133 • Resources res = getResources(); TypedArray icons = res.obtainTypedArray(R.array.icons); Drawable drawable = icons.getDrawable(0); TypedArray colors = res.obtainTypedArray(R.array.colors); int color = colors.getColor(0,0); 134 Commentary • Note that you’ll need these imports in order for the foregoing code to build successfully • (This isn’t difficult, since Quick Fix gives the imports as one possible error solution) • import android.content.res.Resources; • import android.content.res.TypedArray; 135 • It’s also pretty likely you’ll be using drawables in an ImageView • You’ll need this import: • import android.widget.ImageView; 136 • And you’ll have Java code along these lines in your app • • • ImageView myImageView = (ImageView) findViewById(R.id.my_image_view); TypedArray myColorArray = myResources.obtainTypedArray(R.array.color_image_array); myImageView.setImageDrawable(myColorArray.getDrawable(arrayIndex)); 137 • Also remember that when you do resources in this way, when you refer to them, you refer to them by resource type • This is the path in the explorer: • res/values/nameOfFile.xml • This is the reference to it through R in the code: • R.array.nameOfArrayDefinedInFile • You refer to it by the resource type and the name given to the resource, not by path in the explorer or the name of the file 138 Commentary, cont’d. • More words to the wise: • I’m in the habit of copying example XML and code directly out of the API Web page, or more dangerously, from the example XML and code as copied and pasted into these overheads 139 • You need to be forewarned that when you copy in this way you will get mystery characters, some of them completely invisible in the XML itself, that will cause build errors • In the problems tab you’ll get an error like this, without a Quick Fix suggested: • --SomeResourceNameInTheXMLFile cannot be resolved or is not a field-140 • If you go to the LogCat tab you will find something like this after an unsuccessful build: • --Found text “mystery characters” where item tag is expected— • Your XML may be correct (in appearance) • The solution is to retype it in by hand in order to get rid of whatever mystery characters got copied over as a result of copy and paste 141 7.14 Animations • [Animations are included in this list because they are resources. • These overheads will only cover up through the tutorial example of property animation • Even that will be beyond what we can really comprehend 142 • I have little doubt that this is a topic that interested students will want to pursue further • It will be left to the student to do so • In the meantime, we have bigger fish to fry.] 143 • Animation Resources • An animation resource can define one of two types of animations: • Property Animation • Creates an animation by modifying an object's property values over a set period of time with an Animator. • View Animation 144 • There are two types of animations that you can do with the view animation framework: • Tween animation: • Creates an animation by performing a series of transformations on a single image with an Animation • Frame animation: • or creates an animation by showing a sequence of images in order with an AnimationDrawable. 145 • Property Animation • An animation defined in XML that modifies properties of the target object, such as background color or alpha value, over a set amount of time. 146 • • • • • file location: res/animator/filename.xml The filename will be used as the resource ID. compiled resource datatype: Resource pointer to a ValueAnimator, ObjectAnimator, or AnimatorSet. • resource reference: • In Java: R.animator.filename • In XML: @[package:]animator/filename 147 • • syntax: <set android:ordering=["together" | "sequentially"]> <objectAnimator android:propertyName="string" android:duration="int" android:valueFrom="float | int android:valueTo="float | int | android:startOffset="int" android:repeatCount="int" android:repeatMode=["repeat" | android:valueType=["intType" | <animator android:duration="int" android:valueFrom="float | int android:valueTo="float | int | android:startOffset="int" android:repeatCount="int" android:repeatMode=["repeat" | android:valueType=["intType" | | color" color" "reverse"] "floatType"]/> | color" color" "reverse"] "floatType"]/> <set> ... </set> </set> 148 • The file must have a single root element: • either <set>, <objectAnimator>, or <valueAnimator>. • You can group animation elements together inside the <set> element, including other <set> elements. 149 7.15 XML Files • [Following are some comments from the tutorial. • Note that some things have to be saved this way • But you would also have the option of saving things in XML files and then including them in other XML files—if you wanted to.] • Arbitrary XML files that can be read at runtime by calling Resources.getXML(). • Various XML configuration files must be saved here, such as a searchable configuration. 150 7.16 Raw Files • [Following are some comments from the tutorial. • Most of these comments are too advanced to be immediately comprehensible or usable. • The basic point is that your app may use resources which are simply not XML files—they are “actual” resources of some other type. • At the beginning of this set of overheads, in the table of resources, an mp3 file was given as an example.] 151 • Arbitrary files to save in their raw form. • To open these resources with a raw InputStream, call Resources.openRawResource() with the resource ID, which is R.raw.filename. • However, if you need access to original file names and file hierarchy, you might consider saving some resources in the assets/ directory (instead of res/raw/). • Files in assets/ are not given a resource ID, so you can read them only using AssetManager. 152 7.17 Errors 153 • This is another sidetrip, continuing the presentation of errors I have encountered while working on the examples • One of the errors I couldn’t trace to anything I had explicitly done—it just happened • The other, ultimately, was traceable • Either way, it was necessary to solve the problem before going on 154 • There is no particular logic or order to the presentation of these sections on errors • I bring them up as I encounter them • You may or may not encounter these or similar errors when you are working on the same things • The point is that when you have a problem, you’re motivated to learn more so that you can come up with a solution 155 Error One, Configuration • The first error is the one that was untraceable • Maybe you will be lucky and this will never happen to you • All I can say for sure is that at one point I had working code, and later on, without making changes to the code itself, it wouldn’t work 156 • The only questionable things I did in the meantime had to do with updating my installation of Android using the SDK Manager • Either I touched something inadvertently • Or the updating itself caused the problem 157 • When trying to run my formerly valid code, I got this error message in the console: • No active compatible AVD's or devices found. Relaunch this configuration after connecting a device or starting an AVD. 158 • Point 1: I had both a virtual device and a real device attached and up and running just as I had when the app worked OK before • I restarted these things, but to no avail • Point 2: I refreshed, cleaned, and rebuilt my project, thinking maybe there was a compatibility problem due to changes in the versions of the development software • This was also to no avail 159 • After doing the previous 2 things more than once, it finally occurred to me that the key word in the error message might be “configuration” • You may recall that at the very beginning of the course configurations were mentioned • At that time I said we’d just do standard “run” and it wasn’t necessary to mess with the configuration 160 • The time had come to look further into configurations • In the menu, under Run, there are two configuration options: • Run Configurations… • Debug Configurations… • The screen you get from taking the Run Configurations… option is shown on the following overhead 161 162 • The following overhead shows the same screen after you’ve selected the Target tab • In that screen, the first radio button, “Always prompt to pick device” is selected 163 164 • I am still not interested in the depths of configurations • However, I can say that when my program wouldn’t run, one of the other radio buttons was selected • Selecting the first one, so that at run time I could pick the AVD/device I wanted my app to run on, solved my configuration problem 165 • The simple moral of the story at this point is that you can’t totally ignore questions of configuration • Doubtless this will come up again in the future and it will be necessary to learn even more about run configurations and debug configurations 166 Error Two, a Resource Error that Propagated • I started the development of the example of this unit by copying the example of the last unit • That means I started with layouts, (limited other, namely string) resources, and Java code • I made minor modifications to the Java code to confirm for myself that I had the bare bones needed for the new app 167 • At that point I started developing some resource files • I specified a resource, myRedPlusBlue in this way: #FOF (“Oh”) • This was a typographical error (easy for a touch typist to make • It should have been #F0F (zero) 168 • The offending line in the resource file was flagged, but I didn’t see immediately what was wrong and didn’t worry about the consequences • However, when I looked back at my Java code, which I had previously verified, it was now littered with errors 169 • Every line of code that contained a reference to R.java was wrong • The error messages indicated that I was referring to things that didn’t exist • I went to the gen folder in the explorer and discovered that the R.java file wasn’t there 170 • It took some time to realize that the R.java file would not be auto-generated unless everything in the resource files was correct • The system will not auto-generate a partial R.java file for only those resources that are correct • After realizing this, it then took more time to see that I had typed Oh instead of zero and that was the ultimate source of the problem 171 • The moral of the story is that it really is a mess managing multiple files that have to be consistent • Errors in one file can propagate to others in several ways • 1. Errors in one file may cause another file not to be created 172 • 2. Errors in one file or the absence of a file may cause unexpected and cryptic error flagging in other files • This is mysterious, but there’s a logic to it • What is flagged is the thing that the programmer provided which is lacking a necessary antecedent elsewhere 173 • This would be an alternative approach (which I’ve never seen explicitly put into practice): • Insert error messages into the file where the antecedents should be, indicating that something should be there which isn’t, since another file refers to it • (The difficulty of this approach from a compiling point of view is, how do you “flag” something that isn’t there?) 174 7.18 Designing an App • Up until now, the process of making an app was described as consisting of 4 parts: • Making a layout • Making the strings.xml file (conform to the layout) • Noting the auto-generated R.java file corresponding to the layout and strings • Writing the activity.java code 175 • The app for this unit isn’t very complicated, but a small step forward requires reorganizing how we think about app development • We have learned that layouts and strings are both just kinds of resources • We’ve also learned that there are other kinds of resources beyond these 176 • When developing an app it is still reasonable to work visually • You use the layout as a way of thinking about functionality • When you develop the layout, it is also the case that it will become apparent what other resources may be needed in order to support it 177 • For a complex app, you would want to use a well-defined methodology, with graphical components, to develop it • You would specify appearance, functionality, state, transitions, activities, fragments, etc. • Some sort of UML-like system would be needed to capture all of the needed information in design documents 178 • We are still early in the development of apps, and it’s unlikely that we’ll reach the point in one semester where we will learn a methodology • In the meantime, I offer two iterations of a “design document” which I used when trying to develop the example app for this unit, which will be presented shortly 179 • The main points I’m trying to illustrate are the following: • I try to identify screens (boxes) • I try to identify transitions (arrows) • I note both in the boxes and in notes at the bottom the various resources I think I’ll need to accomplish this • The two iterations of the design document are given on the following overheads 180 181 182 • The overall moral of the foregoing, messy documents is this: • I got a clear idea of two things: • I know how many activities/screens my app will consist of • I know what resources the app will need • That’s enough for this simple example • For a more complicated example I would want to nail down more things before starting to do development work 183 Developing an App • As noted already, in the previous units, the development process was given more or less as: • Make a layout, make a strings file, write code • Along the way we dealt with the fact that until one of the components was finished, we were going to get error messages for the others 184 • At this point we confront several considerations: • 1. A single app may have >1 activity, which means >1 distinct piece of source code to work on • 2. Multiple activities imply >1 different layout files • 3. There are many different resource types, potentially stored in different files, which various layouts depend on 185 • 4. Much of the information about resources, etc., has been given using XML code syntax • The Eclipse ADT development environment makes various tools and wizards available to help create and manage resources, layouts, etc. • There is a “cost” in taking the trouble to learn the tools • But the tools can be a great help because they spare you the need to master XML 186 • Frequently, following the directions of a wizard will give a trouble-free result, which trying to write the XML code yourself will lead to troublesome syntax errors • In the following section, some of the uses of the tools for layout and resources will be illustrated • The reality is that app development will tend to involve both XML code writing and tool use 187 • 5. You know my general paradigm of code development: • Copy a working example and figure out how to modify it • This thoroughly mixes up the idea that there might be a fixed order that you create app component files in • You have to beware of the consequences of having resource files and code files in inconsistent states until the point where you’ve finished everything 188 7.19 Using the Graphical Development Tools 189 • Ultimately, at the end of this section, the finished example will be shown • This will involve showing: • The XML and Java code in textual form • Looking at the layouts in graphical form 190 • The catch is that seeing the final result doesn’t show how it was arrived at • I both wrote XML and used the tools • The use of the tools was motivated by the fact that some of the XML I wrote didn’t work • I couldn’t immediately see what was wrong with it, but the tools did the work easily 191 • Afterwards, it was easy to compare my XML with the XML generated by the tools • But the point is that once you’ve seen how the tools work, you have even less reason to try to master the XML anyway • Just use the tools when convenient to generate the XML files you need 192 A Simple XML File • What will be shown next is an XML file with a variety of resources defined in it • I wrote this without using the graphical tools • It works, and it’s given as an illustrative starting point • Ultimately, you want resources put into separate files by type, and you’ll see that the graphical tools follow that model 193 • The example program for this unit does not illustrate the use of every resource type • I decided that in addition to strings, which we’ve seen before, I wanted to try defining and using the following resource types: • An integer • An array of strings • Some colors 194 • The file myassortedresources.xml is shown on the overhead following the next one • The first thing to note is this: The file name has to be all small letters in order to be usable • This file is in the res/values directory • It is a sibling to files like strings.xml and layouts.xml 195 • The system will find this file • Recognize the resources of various types defined in it • And make the corresponding entries in R.java • The syntax of the file contents is simply what was shown in the previous sections of this set of overheads 196 • • • • <?xml version="1.0" encoding="utf-8"?> <resources> <integer name="loopLimit">3</integer> • • • • • • <string-array name="prompt_array"> <item>Welcome</item> <item>Go Again</item> <item>End of the Road</item> </string-array> • • • • • • • • <color <color <color <color <color <color name="myRed">#F00</color> name="myGreen">#0F0</color> name="myBlue">#00F</color> name="myRedPlusGreen">#FF0</color> name="myGreenPlusBlue">#0FF</color> name="myBluePlusRed">#F0F</color> </resources> 197 • In the example I will also make use of a res/drawable-hdpi • Elements of its use will have something in common with the use of the other resources, but it isn’t even presented now • The current discussion will illustrate things with colors only 198 Examples of Tool Use • The foregoing sections went into some detail on the syntax for using resources in code • This is their ultimate use • However, an earlier, simpler use is in layouts themselves • Colors provide a good example of this • Suppose I would like things in layouts to take on certain colors 199 • When writing the XML for the layouts, I can refer to these other resources • The syntax isn’t difficult, but I’m not a master, and I made mistakes • At this point I decided it would be easier to become familiar with the graphical tools than mess more with faulty XML code 200 Step One, Adding Properties to Widgets • What’s shown on the following overhead is a layout with an EditText widget that has been given a color • The color is myBluePlusRed, which was defined in myassortedResources.xml 201 202 • Note that to the right of the graphical display of the layout, if a widget is selected, its properties are shown • The background property is selected and there is a … button next to it • Clicking that button brings up a reference chooser which allows you to choose a resource • This is shown on the following overhead, with myBluePlusRed chosen 203 204 • Notice at the lower left that there is a New Color… button intended to allow you to interactively create a new color at the time of use • The button is not active • Although the latest versions of the ADT should support this function, your installation (like mine) may not 205 • This is true of all of the other resource types— except for String • Even in older installations of the ADT, it is possible to create Strings interactively, as needed • When using a function like this, the newly defined resource would go into the corresponding file, e.g., strings.xml 206 Step Two, Deleting Existing Resources 207 • In order to continue this discussion, I will comment out the colors in myassortedresources.xml: • • • • • • • • <!-<color <color <color <color <color <color --> name="myRed">#F00</color> name="myGreen">#0F0</color> name="myBlue">#00F</color> name="myRedPlusGreen">#FF0</color> name="myGreenPlusBlue">#0FF</color> name="myBluePlusRed">#F0F</color> 208 • After this change, cleaning and rebuilding the project lead to these problems, which were described earlier in the section about errors • My colors aren’t defined, but the layout uses one, so the layout has an error • The R.java file isn’t created • The lack of R.java leads to multiple errors in the code source files that refer to it • This is illustrated in the screen shot on the following overhead 209 210 Step Three, Creating Resource Files • This presentation is actually backwards • In step one you saw how properties can be set and resources created and stored interactively • This suggests that it must be possible to create and populate resource files up front using the graphical tools 211 • The fact that the interactive function isn’t available in your installation isn’t a big deal • You ought to have thought through your resources needs up front • If you have, then you can save yourself even more XML syntax troubles and file naming concerns by using the graphical tools 212 • With step two done, I can now consider how to make a resource file containing colors using the graphical tools • In the explorer, right click on the values folder under res • A pop-up menu will appear with “New” as the first option • Take this option 213 • A new pop-up menu will appear which includes the File and Android XML File option • This set of overheads is only trying to illustrate one path through the options available • Take the plain File option, and you will see what’s shown on the following overhead 214 215 • This is where it becomes critical that you remember the standard names for the files for resources of various types • Enter the file name colors.xml, as shown on the following overhead 216 217 • With luck, after clicking Finish, you will see what’s shown on the following overhead 218 219 • When you click on the New button you will see what’s shown on the following overhead 220 221 • If you select Color, you will see what’s shown on the following overhead 222 223 • The error consists simply of the fact that you haven’t entered a value for your color yet • On the following overhead I show the name and value for the first of the various colors I intend to use in my project 224 225 • Ta-da • What’s shown on the following overhead is what I see if I click on the colors.xml tab instead of the Resources tab 226 227 • If I go back to the Resources tab view, I will be back in the wizard and can enter another color, and continue until I’ve entered them all 228 Step Back and Look • In summing this up, observe the following: • Creating colors (resources) interactively doesn’t seem like the biggest convenience in the world, so the fact that it doesn’t work in my installation isn’t bothersome • Having a feature like that may encourage people not to think their resources out in advance, which isn’t a good idea anyway 229 • Using the wizard to enter the colors up front isn’t really that much easier than typing an XML resource file directly • But maybe it’s a useful convenience • It does illustrate the utility of separating different kinds of resources into their respective files 230 • I do think it’s a great convenience to be able to use the graphical tools to associate a resource with a widget property • Note that in the foregoing overheads, I only showed doing this with the graphical tools • For the sake of completeness, the revised layout file that the tool generates is shown on the following overhead • By using the tool, I avoided having to write some of this XML 231 • <?xml version="1.0" encoding="utf-8"?> • <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" • • • • • • • • • • • xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> • • • • • • • <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_back" android:onClick="sendMessage" /> <TextView android:id="@+id/echo_message" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/myBluePlusRed" /> </LinearLayout> 232 • It’s true that in this example, it’s just one line of XML code I’ve saved writing • But in the long run, I can manage all of the properties of a widget using the graphical tools, and that will tend to be easier than coding and modifying an XML file by hand 233 7.20 Example App with Resources • A complete sequence of screenshots for the app is shown on the following overheads • It alternates between prompting for and displaying an echo 5 times • This echoing corresponds to alternating between activities • The input prompt changes each time • The output cycles through a set of 3 colors • At the end the text color changes, a drawable image is shown, and the button is deactivated 234 235 236 237 • • • • • • • • • The following overheads cover these files: res/values/myassortedresources.xml res/values/strings.xml res/values/colors.xml res/drawable/sleepy2.png res/layout/activity_main.xml res/layout/activity_output_and_back.xml MainActivity.java OutputAndBack.java 238 res/values/myassortedresources.xml • • • • • • • • • • • • • • • • • • • • <?xml version="1.0" encoding="utf-8"?> <resources> <item type="id" name="input_message_view"/> <item type="id" name="output_message_view"/> <item type="id" name="input_button"/> <integer name="numberInColorCycle">3</integer> <integer name="arraySize">6</integer> <string-array name="prompt_array"> <item>Welcome</item> <item>Go Again</item> <item>I\'m getting tired</item> <item>When will it be over?</item> <item>One More Time</item> <item>End of the Road\n***Game Over</item> </string-array> </resources> 239 res/values/strings.xml • • • • • • • • • • • <?xml version="1.0" encoding="utf-8"?> <resources> <string <string <string <string <string <string <string <string name="app_name">Resources ExampleForUnit7</string> name="title_activity_output_and_back">OutputAndBack</string> name="input_message_text">Enter something to echo</string> name="input_button_text">Send</string> name="output_button_text">Back</string> name="action_settings">Settings</string> name="title_activity_main">MainActivity</string> name="title_activity_display_message">My Message</string> </resources> 240 res/values/colors.xml • <resources> • • • • • • <color <color <color <color <color <color • </resources> name="myRed">#F00</color> name="myGreen">#0F0</color> name="myBlue">#00F</color> name="myRedPlusGreen">#FF0</color> name="myGreenPlusBlue">#0FF</color> name="myBluePlusRed">#F0F</color> 241 res/drawable/sleepy2.png 242 res/layout/activity_main.xml • • <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" • • • • xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> • • • • • • • • • • • • <EditText android:id="@id/input_message_view" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/input_message_text" /> <Button android:id="@id/input_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/input_button_text" android:onClick="sendMessage" /> • </LinearLayout> 243 res/layout/activity_output_and_back.xml • • <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" • • • • • • • • • • • xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> • • • • • • • <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/output_button_text" android:onClick="sendMessage" /> <TextView android:id="@id/output_message_view" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/myBluePlusRed" /> </LinearLayout> 244 MainActivity.java • • • • • • • • • • • package com.example.resourcesexampleforunit7; import com.example.resourcesexampleforunit7.OutputAndBack; import com.example.resourcesexampleforunit7.R; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.Button; 245 • public class MainActivity extends Activity { • • public final static String EXTRA_MESSAGE = "com.example.resourcesexampleforunit7.MESSAGE"; public static int arrayIndex = 0; • • • @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); • setContentView(R.layout.activity_main); • • • • • • • • • • • • • • • • • Resources res = getResources(); EditText myEditText = (EditText) findViewById(R.id.input_message_view); String[] prompts = res.getStringArray(R.array.prompt_array); myEditText.setText(prompts[arrayIndex]); if(arrayIndex < res.getInteger(R.integer.arraySize) - 1) { arrayIndex++; } else { Button myButton = (Button) findViewById(R.id.input_button); myButton.setEnabled(false); myEditText.setTextColor(res.getColor(R.color.myBlue)); myEditText.setBackground(res.getDrawable(R.drawable.sleepy2)); } } 246 • • • • • • • • • • • • • • @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public void sendMessage(View view) { Intent intent = new Intent(this, OutputAndBack.class); EditText editText = (EditText) findViewById(R.id.input_message_view); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } } 247 OutputAndBack.java • package com.example.resourcesexampleforunit7; • • • • • • • • import import import import import import import import com.example.resourcesexampleforunit7.R; android.os.Bundle; android.app.Activity; android.content.Intent; android.content.res.Resources; android.view.Menu; android.view.View; android.widget.TextView; 248 • public class OutputAndBack extends Activity { • public final static String EXTRA_MESSAGE = "com.example.resourcesexampleforunit7.MESSAGE"; • public static int colorIndex = 0; • // This would work fine--but it doesn't provide another illustration of the use of a resource. • //public static final int numberInColorCycle = 3; 249 • • • • @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_output_and_back); • • • • // Set the color. Resources res = getResources(); • • • • • • • • • • • • • • • • • • colorIndex = (colorIndex + 1) % (res.getInteger(R.integer.numberInColorCycle)); TextView myTextView = (TextView) findViewById(R.id.output_message_view); if(colorIndex == 0) { myTextView.setBackgroundColor(res.getColor(R.color.myRedPlusGreen)); } else if(colorIndex == 1) { myTextView.setBackgroundColor(res.getColor(R.color.myBluePlusRed)); } else if(colorIndex == 2) { myTextView.setBackgroundColor(res.getColor(R.color.myGreenPlusBlue)); } else { } 250 • • • // Get the message from the intent Intent incomingIntent = getIntent(); String message = incomingIntent.getStringExtra(MainActivity.EXTRA_MESSAGE); • • • // Set the message in the text view of the layout. // Notice how this differs from earlier code, where the // content view was entirely replaced by a new view. • • myTextView.setText(message); } 251 • • • • • • @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.output_and_back, menu); return true; } • • • • • public void sendMessage(View view) { Intent newIntent = new Intent(this, MainActivity.class); startActivity(newIntent); } } 252 Summary and Mission • Summary: Resources… • A large amount of background information was presented • Not every type of resource was covered, and those included were not all covered in detail • The goal was to give enough information so that when you use resources in the future, you will be able to figure out what you need • The background was followed by an example 253 • Mission: You should be able to get an app like the example to work in your environment • Complete code was given for the example • Given the screen shots of the app as your effective design document, if you wanted to you should be able to create the needed resource files and write the code for the app 254 • As usual, there are no graded points for the mission • However, I recommend that you try to get the example to work • The second assignment will build on this example, so performing the mission will be good practice and it will provide you with code that is a starting point for doing the second assignment 255 The End 256