1 / 27

Resources

Resources. Definition: A value or a file bound to an application. Binding to an application Create child directories under the res folder Store files or XML specifications in the child directories Examples Symbolic constants Icons, Pictures, audio, and video Drawable components

toki
Download Presentation

Resources

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Resources Definition: A value or a file bound to an application • Binding to an application • Create child directories under the res folder • Store files or XML specifications in the child directories • Examples • Symbolic constants • Icons, Pictures, audio, and video • Drawable components • UI layouts • XML file specifications • Menus and Layouts

  2. Naming Resource Subdirectories Syntax: <reservedName>[ [-<modifier>] … ]* • Parent Directory: res • Reserved Names: values, layout, drawable, xml, raw, anim • Modifiers: http://developer.android.com/guide/topics/resources/providing-resources.html • Platform versions: -v3, -v2, -v4, etc. • Navigation: -trackball, -wheel, -stylus, -finger, etc. • Keyboard: -12key, -querty, -nokeys • Screen density: -ldpi, -mdpi,-hdpi,-xdpi • Orientation: -land, -port • Screen size: -small, -normal, -large, -xlarge • Screen height or width: -w720dp, -h1024dp, etc. • Language and/or region: -en, -fr, -en-US, -fr, etc. • Examples (Note: for complex specifications, the order is important) • values-fr for Symbolic constants in french • layout-landscape • Complex resource specification: drawable-fr-land-xlarge-v4

  3. Subdirectory Operation • Subdirectories with modifiers • Android first searches the least device-specific directory • Android then searches subdirectories that are more specific • Levels of subdirectories reflect combined device parameters • Subdirectories without modifiers • The default subdirectory has no modifiers (the default) • If a resource does not exist in a subdirectory with modifiers, Android looks for the resource in the default subdirectory • It is wise to always include a default, providing resources for the most common device configuration • Subdirectories with modifiers override the defaults • Runtime exceptions occur when resources cannot be found

  4. Layouts (res/layout/main.xml) <?xml version="1.0" encoding="utf-8"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/note" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/ok" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/button_ok" /> </LinearLayout> fill_parent deprecated replaced with match_parent after version 2.0 + means create symbolic constant if not already defined Java access: setContentView(R.layout.main); // R.layout.file_name mText = (EditText) findViewById(R.id.note); // Get the widget

  5. Symbolic Constants Defined with XML files in one of the res/values subdirectories • Purpose • Localize the values outside the source code • Enables easy changes without modifying code • Enables adaptations for different localities and configurations, without maintaining multiple loads • Examples • res/values-en contains strings in English; res/values-fr contains strings translated to French • res/values-sp contains color combinations that are appropriate to Spanish culture, like yellow for emphasis rather than red

  6. Defining Symbolic Constants • How? Create XML files in the res/values subdirectories • Operation • Android gathers the XML files and merges their contents • Each build automatically generates the file R.java • Stored in a gen subdirectory (gen/com.example.android.notes) • Contains integer codes corresponding to each symbol • Application code addresses these codes using R.<type>.name • XML files references existing codes using @<type>/name • All modifier subfolders should use the same type and name values so the code device and location independent

  7. String Constants • Typically defined in strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="menu_revert">Revert</string> <string name="resolve_edit">Edit note</string> <string name="title_edit">Edit note</string> </resources> • Access from Java code • setTitle(getResources().getText(R.string.title_edit)); • setTitle(activity.getResources().getString(R.string.title_edit)); • menu.add(0, REVERT_ID, 0, R.string.menu_revert) // group,id,order,text • Access from androidManifest.xml: <intent-filter android:label="@string/resolve_edit"> • Note:getString() returns a plain string, getText() can return a styled string Note: For some controls, getResources().getText() is not necessary

  8. Arrays of Strings • String Arrays: strings.xml or any xml file name • Declaration:<string-array name="colors"> <item>red</item><item>green</item><item>blue</item></string-array> • Java: String[] = activity.getResources().getStringArray(R.array.colors); • Plurals: strings.xml or any xml file name • Declaration:<plurals name="group"><item quantity="1">one</item> <item quantity="2">couple</item> <item quantity="3">few</item> <item quantity="other">some</item></plurals> • Java: String s = activity.getResources().getQuantityString(R.plurals.group, 3);

  9. Other Symbolic Constants • Colors: Typically colors.xml • Declaration: <color name="emphasize">#ff0000</color> • Java:activity.getResources.getColor(R.color.emphasize); • Dimensions: Typically dimens.xml; Units of measure are px, in, mm, pt, dp, sp • Declaration: <dimension name="border">5px</dimen> • Java:activity.getResources.getDimension(R.dimen.border); • Attributes: Typically attrs.xml; Customize the application based on parameters • Declaration: <declare-styleable name="styles"> <attr name="tiling"> <flag name="center" value="0"/><flag name="stretch" value="1"/> <flag name="repeat" value="2"/> </attr> • Java: String str = getString(R.styleable.styles.tiling, 2); // Get “repeat” Note: dp or sp = density independent or scale independent pixels

  10. Color Drawable Resources • Declaration: Define in res/values with any xml file name <resources><drawable name="red_rect">#f00</drawable> </resources> • Access in XML <TextView android:layout_width="match_parent" layout_height="wrap_content" android:textAlign:center" android:background="@drawable/red_rect" /> • Java: label.setBackgroundResource(R.drawable.red_rect); Drawables can be bit map pictures: jpg, png, gif or shapes which are Series of rectangles, ovals and polygons, or various other visual effects

  11. Drawable in the background myShape.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <gradient android:centerX="0.5" android:centerY="0.5" /> <solid android:color="#666666"/> <size android:width="120dp" android:height="120dp"/> </shape> Apply to layout <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/myshape" android:orientation="vertical" >

  12. Animations • Step 1: create an animation in XML • Step 2: load the animationa = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade); • Attach listeners to the animation if desireda.setAnimationListener(this); • Apply the animation to a view and starttext.startAnimation(a);

  13. Animation Resources Create flashy animations on an Android device Purpose: vary scale factors, rotations, or colors from a starting to ending value over a period of time • Create an XML file in res/anim • Example: <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator"> <scale android:fromXScale="0" android:toXScale="1" android:fromYScale="0.1" android:toYScale="1.0" android:duration="5000" android:pivotX="50%" android:pivotY="50%” // Zoom from the center android:startOffset="1000" /></set> • Access from Java: R.anim.foo where foo.xml is the file in res/anim

  14. Animation Example <?xml version="1.0" encoding="utf-8" ?> <set xmlns:android=http://schemas.android.com/apk/res/android android:interpolator = "@android:anim/accelerate_interpolator" > <rotate android:fromDegrees="0" android:toDegrees="160" android:pivotX= "50%" android:pivotY= "50%" android:startOffset= "500" android:duration="1000" /> <scale android:fromXScale= "1.0" android:toXScale="0" android:fromYScale= "1.0" android:toYScale= "0" android:pivotX= "50%" android:pivotY= "50%" android:startOffset = "500" android:duration= "500" /> <alpha android:fromAlpha=“1.0“ android:toAlpha="0" android:startOffset= "500" android:duration= "500" /> Accelerate interpolator: starts slowly and accelerates

  15. Animation of List of Pictures Store in file named: android_anim.xml <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot= "false" > <item android:drawable="@drawable/pic1" android:duration="500“/> <item android:drawable="@drawable/pic1" android:duration="500“/> <item android:drawable="@drawable/pic1" android:duration="500“/> </animation-list> ImageView view = (ImageView)findViewById(R.id.IV_android); view.setBackgroundResource(R.drawable.android_anim); AnimationDrawable animation = (AnimationDrawable)androidIV.getBackground(); animation.start(); XML views are identified by an id value

  16. Themes and Styles Definitions Style:A presentation format applied to either views, spannables or entire applications Spannable: A special type of string that can be styled within a view Theme: A style that applies to an entire activity or application

  17. Style Definition 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> …         <item name="[package:]style_property_name"> style_value</item>    </style></resources>

  18. Defining a Style Resource • XML Definition (stored in res/values)<?xml version="1.0" encoding="utf-8"?><resources>    <style name=“MyStyle" parent="@style/Text">        <item name="android:textSize">20sp</item>        <item name="android:textColor">#008</item>    </style></resources> • Usage in a view:<TextViewandroid:id="@+id/errorText" style="@style/MyStyle" /> • Activity theme: <activity android:theme=@style/MyStyle"> • Android Application theme: <application android:theme="@android:style/Theme.NoTitleBar">

  19. Formatting and Styling • Formatting Strings (format is like using the C sprintf method)XML declaration: <string name="hi">Hello, %1$s!</string>Java usage: String text = String.format(context.getString(R.string.hi), user); • Styling a String XML declaration: <string name="bi"> <b><i>bold and italic</b></i> </string> Java usage: textView.setText(Html.fromHtml(R.string.bi), TextView.BufferType.SPANNABLE); • Styling part of a StringXML declaration: <string name=“ital">< i>Italics</i> to emphasize</string>Note: <b>, <i>, <u>, <sup>, <sub>, <strike>,<big>, <small>, <monospace> are ok Java usage: Spannable text = (Spannable)view.getText(); TextAppearanceSpan style = new TextAppearanceSpan(context, R.style, ital); text.setSpan(style, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); Note: applies style from characters 0 to 5 excluding end points

  20. Applying a style to a view • XML declaration:<style name="highlight"> <item name="android:textColor">#ff0000</item> <item name="android:textStyle">bold</item> </style> • Java usage: textView.setTextAppearance(activity, R.style.highlight); • XML usage <EditTextandroid:id="@+id/myEditText“ android:layout_width="match_parent“android:layout_height="wrap_content" android:text="@android:string/httpErrorBadURL" android:style="@style/highlight“ android:textColor="?android:textColor" /> Notes +id/myEditText: Create id if not defined, @android:string/httpErrorBadURL: An android system message, ?android:textColor: Access the current theme’s text color

  21. Refer to a Theme in an Application <manifest xmlns:android=http://schemas.android.com/apk/res/android package="com.myapp.themetest" android:versionCode="1" android:versionName="1.0" > <uses-sdkandroid:minSdkVersion="14" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/Theme.MyAppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

  22. Creating a Style Holo Dark <resources xmlns:android="http://schemas.android.com/apk/res/android"> <style name="Theme.MyAppTheme" parent="android:style/Theme.Holo.Light"> // Inheritance <item name="android:actionBarStyle"> @style/Theme.MyAppTheme.ActionBar</item> </style> <style name="Theme.MyAppTheme.ActionBar" parent="android:style/Widget.Holo.Light.ActionBar"> <item name="android:background">#FF4444</item> </style> // Change color of action bar Holo Light

  23. A popup menu in XML (popup.xml in res/menu folder) <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/refresh" android:title="@string/refresh" /> <item android:id="@+id/settings" android:title="@string/settings" /> </menu> public void CreatePopupMenu(View v) { PopupMenu menu = new PopupMenu(this, v); MenuInflaterinflater = mypopupmenu.getMenuInflater(); inflater.inflate(R.menu.popup, menu.getMenu()); menu.show();  }

  24. Respond to popup menu @Override  public booleanonMenuItemClick(MenuItem arg0) { switch (arg0.getItemId()) { case R.id.refresh: showToast(getText(R.string.refresh));   return true;   case R.id.option2: showToast(getText(R.string.settings));   return true; default:   return super.onContextItemSelected(arg0);  }

  25. Many Resources <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">To Do List</string> <plurals name="androidPlural"> <item quantity="one">One android</item> <item quantity="other">%d androids</item> </plurals> <color name="app_background">#FF0000FF</color> <color name= "app_foreground“>#FFFF”</color> <dimen name="default_border">5dp</dimen> <string-array name="string_array"> <item>Item 1</item> <item>Item 2</item> <item>Item 3</item> </string-array> <array name="integer_array"> <item>3</item><item>2</item><item>1</item> </array> <dimen name="standard_border">5dp</dimen> </resources> Best Practice: put resource categories in their own individual files

  26. File Resources • Images: Drop in a res/drawable subfolder; Codecs: jpg, gif, png • XML files to parse: Drop in a res/xml subfolder • Arbitrary files:Drop in a res/raw subfolder or /assets • Most files are pre-compiled during the build. These files are not • res/raw files have an R.java ID. For example R.raw.foo without an extension for foo.png or foo.txt. This approach requires lower case alphanumeric characters and periods.getResources().openRawResource(R.raw.myfilename). • Files stored in /assets do not have an R.java ID. Access using Java input stream programming using a fully qualified path name.InputStream is = getAssets().open("myFolder/somefile.txt"); • Examples of use: Video files or XML files that the application parses using Java DOM or SAX classes

  27. Third Presentation Implementation of the class project • Describe how it works and give a demo • Use an actual device if possible • Specifically discuss innovations that you implemented • Discuss possible improvements that focus on making the application more exciting for users. • Discuss the advantages or disadvantages of using JavaScript or native Android applications, your preferences, and the reasoning behind your position.

More Related