Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Android 7: Resources Kirk Scott 1

2 2

3 3

4 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

5 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

6 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 7.6 Integers 7.7 Dimensions 7.8 Colors 7.9 Styles 7.10 Layouts 7.11 Menus 7.12 Graphics (Drawables) 7

8 7.13 Typed Arrays (of Drawables) 7.14 Animations 7.15 XML Files 7.16 Raw Files 7.17 Errors 7.18 Designing an App 7.19 Using the Graphical Development Tools 7.20 Example App with Resources 8

9 7.1 Introduction 9

10 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

11 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 12

13 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

14 Resource TypeRequired DirectorySuggested File NamesXML Tag Strings/res/valuesstrings.xml IDs/res/valuesfilename.xml (any file) Integers/res/valuesintegers.xml Dimensions/res/valuesdimens.xml Colors/res/valuescolors.xml Styles/res/valuesstyles.xml Layouts/res/layoute.g., activity_main.xmlVarious layout tags Menus/res/menue.g., mainmenu.xml Graphics/res/drawablee.g., icon.png, logo.png Supported graphics files or drawable definition XML files such as shapes Animations/res/animatore.g., fadesequence.xml, spinsequenc.xml,,,, XML Files/res/xmle.g., data.xmlNo defined tag Raw Files/res/rawe.g., jingle.mp3No defined tag 14

15 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

16 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. String 16

17 String Array XML resource that provides an array of strings. String Array Quantity Strings (Plurals) XML resource that carries different strings for pluralization. Quantity Strings (Plurals) 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.Formatting and Styling [Note that these last two types of resources are not covered in these overheads.] 17

18 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 element. 18

19 file location: res/values/filename.xml The filename is arbitrary. The element's name will be used as the resource ID. compiled resource datatype: Resource pointer to a String.String resource reference: In Java: R.string.string_name In XML:@string/string_name 19

20 syntax: text_string resourcesstring 20

21 elements: Required. This must be the root node. No attributes. 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.Formatting and Styling attributes: name String. A name for the string. This name will be used as the resource ID. 21

22 example: XML file saved at res/values/strings.xml: Hello! 22

23 This layout XML applies a string to a View: 23

24 This application code retrieves a string: String string = getString(R.string.hello); getString You can use either getString(int) or getText(int) to retrieve a string.getString(int) getText(int) getText(int) will retain any rich text styling applied to the string. getText(int) 24

25 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 element. 25

26 file location: res/values/filename.xml The filename is arbitrary. The element's name will be used as the resource ID. compiled resource datatype: Resource pointer to an array of Strings.String resource reference: In Java: R.array.string_array_name 26

27 syntax: text_string resourcesstring-arrayitem 27

28 elements: Required. This must be the root node. No attributes. Defines an array of strings. Contains one or more elements. attributes: name String. A name for the array. This name will be used as the resource ID to reference the array. 28

29 A string, which can include styling tags. The value can be a reference to another string resource. Must be a child of a 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.Formatting and Styling No attributes. 29

30 example: XML file saved at res/values/strings.xml: Mercury Venus Earth Mars 30

31 This application code retrieves a string array: Resources res = getResources(); String[] planets = res.getStringArray(R.array.planets_array);getResources()getStringArray 31

32 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

33 More Resource Types This page defines more types of resources you can externalize, including: Bool XML resource that carries a boolean value. Bool Color XML resource that carries a color value (a hexadecimal color). Color Dimension XML resource that carries a dimension value (with a unit of measure). Dimension 33

34 ID XML resource that provides a unique identifier for application resources and components. ID Integer XML resource that carries an integer value. Integer Integer Array XML resource that provides an array of integers. Integer Array Typed Array XML resource that provides a TypedArray (which you can use for an array of drawables). Typed Array 34

35 [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

36 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

37 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

38 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

39 ID A unique resource ID defined in XML. Using the name you provide in the 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).View 39

40 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 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

41 file location: res/values/filename.xml The filename is arbitrary. resource reference: In Java: R.id.name In XML: @[package:]id/name 41

42 syntax: resourcesitem 42

43 elements: Required. This must be the root node. No attributes. Defines a unique ID. Takes no value, only attributes. attributes: type Must be "id". name String. A unique name for the ID. 43

44 example: XML file saved at res/values/ids.xml: 44

45 Then, this layout snippet uses the "button_ok" ID for a Button widget: 45

46 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

47 [The last example in the subsection on IDs in the tutorials isn’t very helpful, so it is not included.] 47

48 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 element. 48

49 file location: res/values/filename.xml The filename is arbitrary. The 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

50 syntax: integer resourcesinteger 50

51 elements: Required. This must be the root node. No attributes. An integer. attributes: name String. A name for the integer. This will be used as the resource ID. 51

52 example: XML file saved at res/values/integers.xml: 75 5 52

53 This application code retrieves an integer: Resources res = getResources();getResources() int maxSpeed = res.getInteger(R.integer.max_speed);getInteger 53

54 This application code retrieves an integer: Resources res = getResources(); int maxSpeed = res.getInteger(R.integer.max_speed);getResources()getInteger 54

55 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

56 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

57 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

58 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

59 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

60 mm Millimeters - Based on the physical size of the screen. in Inches - Based on the physical size of the screen. 60

61 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 element. 61

62 file location: res/values/filename.xml The filename is arbitrary. The 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

63 syntax: dimension resourcesdimen 63

64 elements: Required. This must be the root node. No attributes. 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

65 example: XML file saved at res/values/dimens.xml: 25dp 150dp 30dp 16sp 65

66 This application code retrieves a dimension: Resources res = getResources(); float fontSize = res.getDimension(R.dimen.font_size);getResources()getDimension 66

67 This layout XML applies dimensions to attributes: 67

68 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

69 The value always begins with a pound (#) character and then followed by the Alpha-Red- Green-Blue information in one of the following formats: #RGB #ARGB #RRGGBB #AARRGGBB [The alpha channel is a measure of transparency] 69

70 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 element. 70

71 file location: res/values/colors.xml The filename is arbitrary. The 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

72 syntax: hex_color resourcescolor 72

73 elements: Required. This must be the root node. No attributes. 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

74 example: XML file saved at res/values/colors.xml: #f00 #80ff0000 74

75 This application code retrieves the color resource: Resources res = getResources(); int color = res.getColor(R.color.opaque_red);getResources()getColor 75

76 This layout XML applies the color to an attribute: 76

77 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).ViewActivity For more information about creating and applying styles, please read Styles and Themes.Styles and Themes 77

78 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 element. 78

79 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

80 syntax: style_value resourcesstyleitem 80

81 elements: Required. This must be the root node. No attributes. 81

82 Defines a single style. Contains 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

83 Defines a single property for the style. Must be a child of a 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

84 example: XML file for the style (saved in res/values/): 20sp #008 84

85 XML file that applies the style to a TextView (saved in res/layout/):TextView 85

86 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

87 Layout Resource A layout resource defines the architecture for the UI in an Activity or a component of a UI. 87

88 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.View resource reference: In Java: R.layout.filename In XML: @[package:]layout/filename 88

89 syntax: ViewGroupViewrequestFocusViewGroupViewinclude 89

90 Note: The root element can be either a ViewGroup, a View, or a element, but there must be only one root element and it must contain the xmlns:android attribute with the android namespace as shown. ViewGroupView 90

91 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

92 Menu Resource A menu resource defines an application menu (Options Menu, Context Menu, or submenu) that can be inflated with MenuInflater.MenuInflater For a guide to using menus, see the Menus developer guide.Menus 92

93 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.Menu resource reference: In Java: R.menu.filename In XML: @[package:]menu.filename 93

94 syntax: menuitem 94

95 groupitem menuitem 95

96 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

97 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. getDrawable(int) 97

98 There are several different types of drawables: Bitmap File A bitmap graphic file (.png,.jpg, or.gif). Creates a BitmapDrawable.BitmapDrawable Nine-Patch File A PNG file with stretchable regions to allow image resizing based on content (.9.png). Creates a NinePatchDrawable.NinePatchDrawable 98

99 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.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.StateListDrawable 99

100 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.LevelListDrawable Transition Drawable An XML file that defines a drawable that can cross-fade between two drawable resources. Creates a TransitionDrawable.TransitionDrawable 100

101 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.ClipDrawable 101

102 Scale Drawable An XML file that defines a drawable that changes the size of another Drawable based on its current level value. Creates a ScaleDrawableScaleDrawable Shape Drawable An XML file that defines a geometric shape, including colors and gradients. Creates a ShapeDrawable.ShapeDrawable 102

103 Also see the Animation Resource document for how to create an AnimationDrawable.Animation ResourceAnimationDrawable Note: A color resource can also be used as a drawable in XML.color resource For example, when creating a state list drawable, you can reference a color resource for the android:drawable attribute (android:drawable="@color/green").state list drawable 103

104 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

105 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]/ˈpɪŋ/ [2]PINGraster graphicsfile format lossless data compression Graphics Interchange Format [3] 105

106 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

107 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.Drawable 107

108 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.BitmapDrawable resource reference: In Java: R.drawable.filename In XML: @[package:]drawable/filename 108

109 example: With an image saved at res/drawable/myimage.png, this layout XML applies the image to a View: 109

110 The following application code retrieves the image as a Drawable:Drawable Resources res = getResources(); Drawable drawable = res.getDrawable(R.drawable.myimage);getResources()getDrawable 110

111 see also: 2D Graphics2D Graphics BitmapDrawable 111

112 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

113 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

114 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

115 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

116 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

117 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

118 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

119 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

120 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 120

121 Commentary cont’d. This runtime error went away when I got rid of the plus sign in the XML 121

122 7.13 Typed Arrays (of Drawables) Typed Array A TypedArray defined in XML.TypedArray You can use this to create an array of other resources, such as drawables. 122

123 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.TypedArray 123

124 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 element. 124

125 file location: res/values/filename.xml The filename is arbitrary. The element's name will be used as the resource ID. 125

126 compiled resource datatype: Resource pointer to a TypedArray.TypedArray resource reference: In Java: R.array.array_name In XML: @[package:]array.array_name 126

127 syntax: resource resourcesarrayitem 127

128 elements: Required. This must be the root node. No attributes. 128

129 Defines an array. Contains one or more child elements. attributes: android:name String. A name for the array. This name will be used as the resource ID to reference the array. 129

130 A generic resource. The value can be a reference to a resource or a simple data type. Must be a child of an element. No attributes. 130

131 example: XML file saved at res/values/arrays.xml: 131

132 @drawable/home @drawable/settings @drawable/logout #FFFF0000 #FF00FF00 #FF0000FF 132

133 This application code retrieves each array and then obtains the first entry in each array: 133

134 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);getResources()obtainTypedArraygetDrawableobtainTypedArraygetColor 134

135 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

136 It’s also pretty likely you’ll be using drawables in an ImageView You’ll need this import: import android.widget.ImageView; 136

137 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

138 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

139 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

140 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

141 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

142 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

143 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

144 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.Animator View Animation 144

145 There are two types of animations that you can do with the view animation framework: Tween animation: Tween animation Creates an animation by performing a series of transformations on a single image with an Animation Animation Frame animation: Frame animation or creates an animation by showing a sequence of images in order with an AnimationDrawable.AnimationDrawable 145

146 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

147 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.ValueAnimator ObjectAnimatorAnimatorSet resource reference: In Java: R.animator.filename In XML: @[package:]animator/filename 147

148 syntax:... setobjectAnimatoranimatorset 148

149 The file must have a single root element: either,, or. You can group animation elements together inside the element, including other elements. 149

150 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().Resources.getXML() Various XML configuration files must be saved here, such as a searchable configuration.searchable configuration 150

151 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

152 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.InputStreamResources.openRawResource() 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.AssetManager 152

153 7.17 Errors 153

154 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

155 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

156 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

157 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

158 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

159 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

160 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

161 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 162

163 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 164

165 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

166 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

167 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

168 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

169 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

170 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

171 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

172 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

173 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

174 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

175 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

176 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

177 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

178 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

179 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

180 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 181

182 182

183 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

184 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

185 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

186 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

187 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

188 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

189 7.19 Using the Graphical Development Tools 189

190 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

191 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

192 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

193 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

194 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

195 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

196 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

197 3 <string-array name="prompt_array"> Welcome Go Again End of the Road #F00 #0F0 #00F #FF0 #0FF #F0F 197

198 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

199 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

200 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

201 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 202

203 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 204

205 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

206 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

207 Step Two, Deleting Existing Resources 207

208 In order to continue this discussion, I will comment out the colors in myassortedresources.xml: <!-- #F00 #0F0 #00F #FF0 #0FF #F0F --> 208

209 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 210

211 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

212 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

213 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

214 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 215

216 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 217

218 With luck, after clicking Finish, you will see what’s shown on the following overhead 218

219 219

220 When you click on the New button you will see what’s shown on the following overhead 220

221 221

222 If you select Color, you will see what’s shown on the following overhead 222

223 223

224 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 225

226 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 227

228 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

229 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

230 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

231 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

232 <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"> <TextView android:id="@+id/echo_message" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/myBluePlusRed" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_back" android:onClick="sendMessage" /> 232

233 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

234 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 235

236 236

237 237

238 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

239 res/values/myassortedresources.xml 3 6 <string-array name="prompt_array"> Welcome Go Again I\'m getting tired When will it be over? One More Time End of the Road\n***Game Over 239

240 res/values/strings.xml Resources ExampleForUnit7 OutputAndBack Enter something to echo Send Back Settings MainActivity My Message 240

241 res/values/colors.xml #F00 #0F0 #00F #FF0 #0FF #F0F 241

242 res/drawable/sleepy2.png 242

243 res/layout/activity_main.xml <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" /> 243

244 res/layout/activity_output_and_back.xml <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"> <TextView android:id="@id/output_message_view" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/myBluePlusRed" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/output_button_text" android:onClick="sendMessage" /> 244

245 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

246 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

247 @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

248 OutputAndBack.java package com.example.resourcesexampleforunit7; 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.TextView; 248

249 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

250 @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

251 // 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

252 @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

253 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

254 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

255 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

256 The End 256


Download ppt "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."

Similar presentations


Ads by Google