Module 3 Creating and Managing Resources.pdf

Full Transcript

Mobile Application Design and development 1 [Introduction to Android Operating Systems] Module 3: Creating and Managing Resources...

Mobile Application Design and development 1 [Introduction to Android Operating Systems] Module 3: Creating and Managing Resources Course Learning Outcomes: 1. Creating Resources 2. Using Resources 3. Referencing Resources Creating Resources Application resources are stored under the res/ folder of your project hierarchy. In this folder, each of the available resource types can have a subfolder containing its resources. If you start a project using the ADT wizard, it will create a res folder that contains subfolders for the values, drawable, and layout resources that contain the default layout, application icon, and string resource defi nitions, respectively, as shown in Figure 3-1. There are seven primary resource types that have different folders: simple values, drawables, layouts, animations, XML, styles, and raw resources. When your application is built, these resources will be compiled as efficiently as possible and included in your application package. This process also creates an R class fi le that contains references to each of the resources you include in your project. This lets you reference the resources in your code, with the advantage of design time syntax checking. The following sections describe the specifi c resource types available within these categories and how to create them for your applications. In all cases, the resource filenames should contain only lowercase letters, numbers, and the period (.) and underscore (_) symbols. Figure 3-1. /res folder Course Module Creating Simple Values Supported simple values include strings, colors, dimensions, and string or integer arrays. All simple values are stored within XML files in the res/values folder. Within each XML file, you indicate the type of value being stored using tags as shown in the sample XML file below: 1 2 3 To Do List 4 #FF00FF 5 5px 6 7 Item 1 8 Item 2 9 Item 3 10 11 12 3 13 2 14 1 15 16 This example includes all of the simple value types. By convention, resources are separated into separate files for each type; for example, res/values/strings.xml would contain only string resources. To be able to create each page intended for several value types, right click the res folder, select New and click on Android XML File, as shown in Figure 3-2 on the next page. The following sections detail the options for defining simple resources. Strings Externalizing your strings helps maintain consistency within your application and makes it much easier to create localized versions. String resources are specified using the string tag as shown in the following XML snippet: Mobile Application Design and development 3 [Introduction to Android Operating Systems] Stop. Android supports simple text styling, so you can use the HTML tags , , and to apply bold, italics, or underlining to parts of your text strings as shown in the example below: Stop. You can use resource strings as input parameters for the String.format method. However, String.format does not support the text styling described above. To apply styling Figure 3-2. Creating a New XML File to a format string, you have to escape the HTML tags when creating your resource, as shown below: <b>Stop</b>. %1$s Within your code, use the Html.fromHtml method to convert this back into a styled character sequence: 1 String rString = getString(R.string.stop_message); 2 String fString = String.format(rString, “Collaborate and listen.”); 3 CharSequence styledString = Html.fromHtml(fString); Colors Use the color tag to defi ne a new color resource. Specify the color value using a # symbol followed by the (optional) alpha channel, then the red, green, and blue values using one or two hexadecimal numbers with any of the following notations: ❑ #RGB ❑ #RRGGBB ❑ #ARGB ❑ #ARRGGBB The following example shows how to specify a fully opaque blue and a partially transparent green: #00F #7700FF00 Course Module Dimensions Dimensions are most commonly referenced within style and layout resources. They’re useful for creating layout constants such as borders and font heights. To specify a dimension resource, use the dimen tag, specifying the dimension value, followed by an identifier describing the scale of your dimension: ❑ px Screen pixels ❑ in Physical inches ❑ pt Physical points ❑ mm Physical millimeters ❑ dp Density-independent pixels relative to a 160-dpi screen ❑ sp Scale-independent pixels These alternatives let you define a dimension not only in absolute terms, but also using relative scales that account for different screen resolutions and densities to simplify scaling on different hardware. The following XML snippet shows how to specify dimension values for a large font size and a standard border: 5px 16sp Drawables Drawable resources include bitmaps and NinePatch (stretchable PNG) images. They are stored as individual files in the res/drawable folder. The resource identifier for a bitmap resource is the lowercase filename without an extension. The preferred format for a bitmap resource is PNG, although JPG and GIF files are also supported. NinePatch (or stretchable) images are PNG files that mark the parts of an image that can be stretched. NinePatch images must be properly defi ned PNG files that end in.9.png. The resource identifier for NinePatches is the fi lename without the trailing.9.png. A NinePatch is a variation of a PNG image that uses a 1-pixel border to define the area of the image that can be stretched if the image is enlarged. To create a NinePatch, draw single-pixel black lines that represent stretchable areas along the left and top borders of your image. The Mobile Application Design and development 5 [Introduction to Android Operating Systems] unmarked sections won’t be resized, and the relative size of each of the marked sections will remain the same as the image size changes. NinePatches are a powerful technique for creating images for the backgrounds of Views or Activities that may have a variable size; for example, Android uses NinePatches for creating button backgrounds. Using Resources As well as the resources you create, Android supplies several system resources that you can use in your applications. The resources can be used directly from your application code and can also be referenced from within other resources (e.g., a dimension resource might be referenced in a layout definition). Using Resources in Code You access resources in code using the static R class. R is a generated class based on your external resources and created by compiling your project. The R class contains static subclasses for each of the resource types for which you’ve defi ned at least one resource. For example, the default new project includes the R.string and R.drawable subclasses. If you are using the ADT plug-in in Eclipse, the R class will be created automatically when you make any change to an external resource file or folder. R is a compiler-generated class, so don’t make any manual modifications to it as they will be lost when the fi le is regenerated. Each of the subclasses within R exposes its associated resources as variables, with the variable names matching the resource identifiers — for example, R.string.app_name or R.drawable.icon. The value of these variables is a reference to the corresponding resource’s location in the resource table, not an instance of the resource itself. Where a constructor or method, such as setContentView, accepts a resource identifier, you can pass in the resource variable, as shown in the code snippet below: 1 // Inflate a layout resource. 2 setContentView(R.layout.main); Course Module 3 // Display a transient dialog box that displays the 4 // error message string resource. 5 Toast.makeText(this, R.string.app_error, Toast.LENGTH_LONG).show(); When you need an instance of the resource itself, you’ll need to use helper methods to extract them from the resource table, represented by an instance of the Resources class. Because these methods perform lookups on the application’s resource table, these helper methods can’t be static. Use the getResources method on your application context as shown in the snippet below to access your application’s Resource instance: Resources myResources = getResources(); The Resources class includes getters for each of the available resource types and generally works by passing in the resource ID you’d like an instance of. The following code snippet shows an example of using the helper methods to return a selection of resource values: 1 Resources myResources = getResources(); 2 CharSequence styledText = myResources.getText(R.string.stop_message); 3 Drawable icon = myResources.getDrawable(R.drawable.app_icon); 4 int opaqueBlue = myResources.getColor(R.color.opaque_blue); 5 float borderWidth = myResources.getDimension(R.dimen.standard_border); 6 String[] stringArray; 7 stringArray = myResources.getStringArray(R.array.string_array); 8 int[] intArray = myResources.getIntArray(R.array.integer_array); Referrencing Resources You can also reference resources to use as attribute values in other XML resources. This is particularly useful for layouts and styles, letting you create specialized variations on themes and localized strings and graphics. It’s also a useful way to support different images and spacing for a layout to ensure that it’s optimized for different screen sizes and resolutions. To reference one resource from another, use @ notation, as shown in the following snippet: attribute=”@[packagename:]resourcetype/resourceidentifier” Mobile Application Design and development 7 [Introduction to Android Operating Systems] Android will assume you’re using a resource from the same package, so you only need to fully qualify the package name if you’re using a resource from a different package. The following snippet creates a layout that uses color, dimension, and string resources: 1 2 8 15 Course Module References and Supplementary Materials Online Supplementary Reading Materials https://www.javaworld.com/article/3095406/android-studio-for-beginners-part-1- installation-and-setup.html https://developer.android.com/reference/android/content/res/Resources https://www.tutorialspoint.com/android/android_resources.htm

Use Quizgecko on...
Browser
Browser