Style Sheets (CSS)

28
Resources Binding to an application – Create child directories under the res folder – Store files or XML specifications in the child directories Examples – Symbolic constants for primitives and arrays – Icons, Pictures, audio, and video – Drawable and style components – UI layouts – XML file specifications – Menus and Layouts efinition: A value or a file bound to an applicatio

description

Style Sheets (CSS). Separate structure (HTML tags) from browser presentation Control a site’s look and feel Three types Inline : apply to a single HTML tag Document level : apply to groups of a document’s tags External : apply to groups of tags in a set of web site documents - PowerPoint PPT Presentation

Transcript of Style Sheets (CSS)

Page 1: Style Sheets (CSS)

Resources

• Binding to an application– Create child directories under the res folder– Store files or XML specifications in the child directories

• Examples– Symbolic constants for primitives and arrays– Icons, Pictures, audio, and video– Drawable and style components– UI layouts– XML file specifications– Menus and Layouts

Definition: A value or a file bound to an application

Page 2: Style Sheets (CSS)

Naming Resource Subdirectories • 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

Syntax: <reservedName>[ [-<modifier>] … ]*

Page 3: Style Sheets (CSS)

res/values Subdirectories–The default subdirectory has no modifiers–If a resource does not exist in a subdirectory with modifiers, Android uses the default–Without a default, program crashes when encountering an unexpected device configuration–Subdirectories with modifiers override the defaults–Modifiers must be added in a precice order

Page 4: Style Sheets (CSS)

Modifier order

1. Country code (mcc310) mcc = mobile country code

2. Language and region (en, fr, en-rUS, …)3. Layout direction (ldrtl, ldltr)4. Smallest width (sw320dp, …)5. Availble width (w1024dp, …)6. Available height (h720dp, …)7. Screen size (small, normal, large,

xlarge)8. Screen aspect ratio (long, notlong)9. Round screen (round, notround)10. Orientation (land, port)

11. UI mode (television, watch, … )12. Night mode (night, notnight)13. Pixel density (ldpi, mdpi, hdpi,

xhdpi, …)14. Touch screen (notouch, finger)15. Keyboard (keysexposed,

keyshidden, …)16. Input method (querty, 12key, …)17. Navigation availability

(navhidden, navexposed)18. Navigation method (wheel,

trackpad, …)19. Version (v3, v4, v7, …)

Page 5: Style Sheets (CSS)

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>

+ means create symbolic constant if not already defined

fill_parent deprecated replaced with match_parent after version 2.0

Java access: setContentView(R.layout.main); // R.layout.file_namemText = (EditText) findViewById(R.id.note); // Get the widget

Page 6: Style Sheets (CSS)

Symbolic Constants

• 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

Defined with XML files in one of the res/values subdirectories

Page 7: Style Sheets (CSS)

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

Page 8: Style Sheets (CSS)

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

Page 9: Style Sheets (CSS)

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);

Page 10: Style Sheets (CSS)

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

Page 11: Style Sheets (CSS)

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 areSeries of rectangles, ovals and polygons, or various other visual effects

Page 12: Style Sheets (CSS)

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

Page 13: Style Sheets (CSS)

Animations1. Step 1: create an animation in XML2. Step 2: load the animation

a = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade);

3. Attach listeners to the animation if desired

a.setAnimationListener(new AnimationListener(){ void onAnimationStart(Animation animation) { /* code */ }

void onAnimationEnd(Animation animation) { /* code */ }

void onAnimationRepeat(Animation animation) { /* code */}});

1. Apply the animation to a view and start

text.startAnimation(a);

Page 14: Style Sheets (CSS)

Animation Resources

• 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

centerandroid:startOffset="1000"

/></set>

• Access from Java: R.anim.foo where foo.xml is the file in res/anim

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

Page 15: Style Sheets (CSS)

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

Page 16: Style Sheets (CSS)

Animation of List of Pictures

<animation-listxmlns:android="http://schemas.android.com/apk/res/android"android:oneshot= "false" >

<item android:drawable="@drawable/pic1" android:duration="500“/><item android:drawable="@drawable/pic2" android:duration="500“/><item android:drawable="@drawable/pic3" 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();

Store in file named: android_anim.xml

Page 17: Style Sheets (CSS)

Themes and Styles

Style:

A presentation format for either views, spannables or application

Spannable:

A special type of string that can be styled within a view

Theme:

A set of styles that applies to an entire activity or application

Definitions

Page 18: Style Sheets (CSS)

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>

Page 19: Style Sheets (CSS)

Defining a Style Resource

• XML Definition (stored in res/values/styles.xml)<?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:<TextView android:id="@+id/errorText" style="@style/MyStyle" />

• Activity theme: <activity android:theme=@style/MyStyle">• Android Application theme:

<application android:theme="@android:style/Theme.NoTitleBar">

Page 20: Style Sheets (CSS)

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

Page 21: Style Sheets (CSS)

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<EditText android: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

Page 22: Style Sheets (CSS)

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-sdk android:minSdkVersion="14" android:targetSdkVersion="15" /><application android:icon="@drawable/ic_launcher"

android:label="@string/app_name" android:theme="@style/CustomActionBarTheme" >

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

Page 23: Style Sheets (CSS)

Creating a Style

<?xml version="1.0" encoding="utf-8"?><resources><style name=“CustomActionBarTheme" // // Inheritance

parent=“@android:style/Theme.Holo.Light.DarkActionBar"><item name="android:actionBarStyle">@style/MyActionBarr</item>

</style> <style name=“MyActionBar"

parent="android:style/Widget.Holo.Light.ActionBar.Solid.Inverse"> <item name="android:background">#FF4444</item>

</style> // Change color of action bar</resources>

Holo LightHolo Dark

<?xml version="1.0" encoding="utf-8"?><resources>

Note: @drawable/actionbar_background is better

Page 24: Style Sheets (CSS)

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>

Page 25: Style Sheets (CSS)

Popup: attaching and respondingpopup = new PopupMenu(MainActivity.this, button);  popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());  popup.setOnMenuItemClickListener (new PopupMenu.OnMenuItemClickListener()  {   public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.refresh: showToast(getText(R.string.refresh)); return true; // option handled case R.id.settings: showToast(getText(R.string.settings));

return true; // option handled default: return super.onContextItemSelected(item);

}  return true;        }   });  

Note: popup is an instance variableTo make it appear: popup.show();

Page 26: Style Sheets (CSS)

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

Many Resources

Best Practice: put resource categories

in their own individual files

Page 27: Style Sheets (CSS)

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

Page 28: Style Sheets (CSS)

Optional Presentation

Implementation of the class project

1. Describe how it works and give a demo2. Use an actual device if possible3. Specifically discuss innovations that you implemented4. Discuss possible improvements that focus on making the

application more exciting for users.5. Discuss the advantages or disadvantages of using JavaScript

or native Android applications, your preferences, and the reasoning behind your position.