Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Criminal Intent Second through Fouth Lab Projects • Purpose: Records and details office “crimes” • What is an office crime? Examples • • o Leaving trash around o Not cleaning after using the kitchen area Functionality o Maintains titles, pictures, description, etc. o Integrates with e-mail, Facebook, Twitter, etc. Design o Introduces Fragments o Uses a List-detail interface List-Detail Interface Accommodates different devices based on available screen dimensions Fragments A fully reusable application component with its own lifecycle • Runs on the Applications UI thread • Launched by an activity which controls its life cycle using its fragment manager • Fragment are self-contained and reusable • Enables a more flexible application design • Plugs into a portin fo an activity’s view • Can by dynamic or fixed into a layout’s XML file Fragment Back Stack Pressing the back button shows the previous activity, not the previous fragment To add the fragment to the fragment back stack, use the addToBackStack() method Also override the onBackPressed method @Override public onBackPressed() { if (getFragmentManager().getBackStackEntryCount() > 0) { getFragmentManager().popBackStack(); } else { super.onBackPressed(); } } Software Design Criminal Intent MVC Design Fragment Life Cycle Order of Methods called 1) OnAttached() 2) onCreae() 3) onCreateView() Differences from Activites 1) Methods public, not protected 2) OnCreate() Set instance variables 3) OnCreateView() Inflate and return view Methods are called by the activity not from the Android OS FragmentManager Object used by activities to manage a Fragment’s life-cycle Definition: A transaction is a series of operations that is atomic (all done without being interrupted in the middle) FragmentManager operates using transactions FragmentManager fm = getSupportFragmentManager(R.id.fragment_container); Fragment fragment = fm.findFragmentById(R.id.fragment_container); If (fragment == null) { fragment = new CrimeFragment(); fm.beginTransaction() .add(R.id.fragment_container, fragment) .commit(); } Android Compatibility Current Version Build.SDK_INT Forward Compatible • Older device features guaranteed to work on newer devices • Features might not have the expected look on newer devices Backwards Compatible • New features work on older devices • How? o By using the android support library o Package: Android.support.v4.app o Use FragmentSupportManager, not FragmentManager (the native current version) YAGNI and AUF • YAGNI: You Aren’t going to use it o Don’t implement things based on possible future needs o Extra cost of implementation cluttering up the code • AUF: Always use Fragments o The text uses this approach even though many applications don’t need them o Why? Because converting from non-fragments to fragments is a bug-prone process Fragments are far more efficient than launching and interacting with activities (No OS involvement) Steps to Implement Fragments • Layouts o Activity layouts with FrameLayout at fragment plug in spots o Layout for the fragments • Resources: strings, dimensions, colors, etc. • Activity code: FragmentSupportManager to launch the fragment (either in onCreate or in a listener) • Fragment Code: o Override onCreate() to set instance variables o Override onCreateView() to inflate and return the view o Override listener methods o Interact with the launching activity and other fragments Abstract Parent Class • Criminal Intent has two activites o One for a single crime (the one selected) o One for the list (to click to select) • Both activities use fragments • Both use identical code for launching the fragment • To reuse of code, it makes sense to insert common code in a parent abstract class Singletons • The text makes frequent use of singletons (Example: The CrimeLab class in CriminalIntent • Definition: A Singleton is a class that can only have one instance • Plusses o The singleton can be accessed from anywhere in the application o Singletons survive screen rotations • Minuses o It is easy to overuse the concept, basically making too many things static o Many developers frown on their use and prefer other techniques Launching Fragments with data • Two approaches 1. Activity instantiates an intent and bundles data with putExtra() call. The launched fragment extracts the data. 2. Activity calls fragment static method to instantiate an intent with data wrapped into its argument bundle (new Bundle(), putSerializable(), and setArguments() • The second approach is best-practice because fragments should be self-contained without knowledge of the launching activity. Launch and Return data from fragments • An Initiating fragment calls a static method in the activity to be launched (newIntent()) to instantiate an appropriate intent. Then calling startActivityForResult launches the activity • The activity, when launched, commits a translation to launch a fragment. To do this, it calls a static fragment method that instantiates and bundles any necessary arguments. • After the launch, the fragment calls getActivity().setResult() to instantiate an intent containing data to return • When the Initiating fragment resumes, it’s onActivityResult() listener calls a fragment static method to extract returned data from the intent that is returned. The launched activity and fragment are totally self-contained, and are independent from the launching module Recycler View • Similar to ListView but with more flexibility • Supports a scrollable list of GUI views • Helper classes o ViewHolder: Find Components of the view of a particular item and attach listeners o ViewAdapter: Interface between the RecyclerView and the Data Model • Implementation: Layout for the RecyclerView, Layout for each item, Implement ViewHolder and ViewAdapter RecyclerView Operation Criminal Intent Lab 2 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 for primitives and arrays Icons, Pictures, audio, and video Drawable and style components UI layouts XML file specifications Menus and Layouts 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 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 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, …) 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" > fill_parent deprecated replaced with match_parent after version 2.0 <TextView android:id="@+id/note" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> + means create symbolic constant if not already defined <Button android:id="@+id/ok" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/button_ok" /> </LinearLayout> Java access: setContentView(R.layout.main); // R.layout.file_name mText = (EditText) findViewById(R.id.note); // Get the widget 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 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 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 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); 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 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 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" > Animations 1. Step 1: create an animation in XML 2. 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); 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 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 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/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(); Themes and Styles Definitions 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 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> 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"> 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 String XML 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 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 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> <?xml version="1.0" encoding="utf-8"?> <resources> Creating a Style Holo Dark Holo Light <?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> Note: @drawable/actionbar_background is better 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> Popup: attaching and responding popup = 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 variable } To make it appear: popup.show(); }); <?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> Best Practice: put <array name="integer_array"> resource categories <item>3</item><item>2</item><item>1</item> in their own </array> individual files <dimen name="standard_border">5dp</dimen> </resources> Many Resources 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