Slide 1

Slide 1 text

XYZReader Codelab +Yuichi Araki +Jan-Felix Schmakeit +Android Developers Making Apps Beautiful

Slide 2

Slide 2 text

Developer Resources Find out more: + Android Developers Android Developers on YouTube Android Developers Blog http://developer.android.com

Slide 3

Slide 3 text

DevByte Series: “Making Apps Beautiful” “Making Apps Beautiful” DevBytes series on +Android Developers http://bit.ly/14xbcD0

Slide 4

Slide 4 text

Codelab Format Slides, Worksheet, Code 6 Checkpoints Ask our friendly Teaching Assistants Material: http://bit.ly/18EhXuo

Slide 5

Slide 5 text

EXAMPLE TREATMENT

Slide 6

Slide 6 text

Our Agenda 0: Get Set up 1: Modernising and ActionBarCompat 2: Branding 3: Spacing and Typography 4: Tablet UI 5: Bitmap Performance 6: Threading 7: Image Caching

Slide 7

Slide 7 text

Prerequisites

Slide 8

Slide 8 text

Required Downloads IDE for Android Development: http://developer.android.com/sdk •ADT Bundle (Eclipse + Android SDK) •Bonus: Android Studio Android SDK, API 18 Support Library (already included in codelab archive)

Slide 9

Slide 9 text

Required Devices Devices or Emulators: >= Android 4.0 Android 2.3.x Tablet

Slide 10

Slide 10 text

Checkpoint 0: Get set up

Slide 11

Slide 11 text

Checkpoint 0 Worksheet: Checkpoint 0 http://bit.ly/18EhXuo What you will do: •Setup IDE and environment •Import Project •Run the app

Slide 12

Slide 12 text

Checkpoint 1: Modernising, ActionBarCompat

Slide 13

Slide 13 text

EXAMPLE TREATMENT FOR DEVELOPERS AndroidManifest.xml: android:targetSdkVersion = 18 ...

Slide 14

Slide 14 text

EXAMPLE TREATMENT FOR DEVELOPERS AndroidManifest.xml: android:targetSdkVersion = 18 Set your target SDK ...

Slide 15

Slide 15 text

EXAMPLE TREATMENT FOR DEVELOPERS AndroidManifest.xml: android:targetSdkVersion = 18 Set your target SDK ...

Slide 16

Slide 16 text

EXAMPLE TREATMENT FOR DEVELOPERS AndroidManifest.xml: android:targetSdkVersion = 18 ...

Slide 17

Slide 17 text

EXAMPLE TREATMENT

Slide 18

Slide 18 text

EXAMPLE TREATMENT Holo Theme + (compatible) Action Bar

Slide 19

Slide 19 text

EXAMPLE TREATMENT

Slide 20

Slide 20 text

EXAMPLE TREATMENT FOR DEVELOPERS ActionBarCompat in Support Library

Slide 21

Slide 21 text

EXAMPLE TREATMENT FOR DEVELOPERS ActionBarCompat in Support Library Use ActionBarCompat

Slide 22

Slide 22 text

EXAMPLE TREATMENT FOR DEVELOPERS Extend ActionBarActivity Use ActionBarCompat public class ArticleDetailActivity extends ActionBarActivity FragmentActivity { ... } public class ArticleListActivity extends ActionBarActivity FragmentActivity { ... }

Slide 23

Slide 23 text

EXAMPLE TREATMENT FOR DEVELOPERS ActionBar options in ActionBarCompat: Use support-callbacks Use ActionBarCompat @Override public void onCreateSupportOptionsMenu(Menu menu, MenuInflater inflater) { ... } @Override public boolean onSupportOptionsItemSelected(MenuItem item) { ... }

Slide 24

Slide 24 text

EXAMPLE TREATMENT FOR DEVELOPERS Menus in ActionBarCompat: Need to define your own namespace Use ActionBarCompat In your menu.xml, add the following namespace:

Slide 25

Slide 25 text

EXAMPLE TREATMENT FOR DEVELOPERS Menus in ActionBarCompat: Need to define your own namespace Use ActionBarCompat In your menu.xml, add the following namespace:

Slide 26

Slide 26 text

EXAMPLE TREATMENT FOR DEVELOPERS Menus in ActionBarCompat: Need to define your own namespace In your menu.xml, add the following namespace:

Slide 27

Slide 27 text

EXAMPLE TREATMENT FOR DEVELOPERS android:theme = Theme.Holo.Light.DarkActionBar

Slide 28

Slide 28 text

EXAMPLE TREATMENT FOR DEVELOPERS android:theme = Theme.Holo.Light.DarkActionBar Holo Theme + Action Bar

Slide 29

Slide 29 text

EXAMPLE TREATMENT FOR DEVELOPERS android:theme = Theme.Holo.Light.DarkActionBar

Slide 30

Slide 30 text

EXAMPLE TREATMENT FOR DEVELOPERS Application theme MUST inherit from Theme.AppCompat.* Styling your ActionBar <item name="actionBarStyle">@style/Widget.Styled.ActionBar</item> <item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item> <item name="background">@drawable/bg_striped</item> <item name="android:background">@drawable/bg_striped</item> ...

Slide 31

Slide 31 text

EXAMPLE TREATMENT FOR DEVELOPERS Application theme MUST inherit from Theme.AppCompat.* Use ActionBarCompat Styling your ActionBar <item name="actionBarStyle">@style/Widget.Styled.ActionBar</item> <item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item> <item name="background">@drawable/bg_striped</item> <item name="android:background">@drawable/bg_striped</item> ...

Slide 32

Slide 32 text

EXAMPLE TREATMENT FOR DEVELOPERS Application theme MUST inherit from Theme.AppCompat.* Styling your ActionBar <item name="actionBarStyle">@style/Widget.Styled.ActionBar</item> <item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item> <item name="background">@drawable/bg_striped</item> <item name="android:background">@drawable/bg_striped</item> ...

Slide 33

Slide 33 text

Checkpoint 1 Worksheet: Checkpoint 1 http://bit.ly/18EhXuo What you will do: •Set the targetSDK •Add ActionBarCompat

Slide 34

Slide 34 text

Checkpoint 2: Custom ActionBar Styles

Slide 35

Slide 35 text

EXAMPLE TREATMENT

Slide 36

Slide 36 text

EXAMPLE TREATMENT Branded Color Scheme + App Icon

Slide 37

Slide 37 text

EXAMPLE TREATMENT

Slide 38

Slide 38 text

EXAMPLE TREATMENT FOR DEVELOPERS Search Google for “Action Bar Style Generator”: Android Action Bar Style Generator by Jeff Gilfelt Style Compatibility AppCompat

Slide 39

Slide 39 text

EXAMPLE TREATMENT Branded Color Scheme + App Icon FOR DEVELOPERS Search Google for “Action Bar Style Generator”: Android Action Bar Style Generator by Jeff Gilfelt Style Compatibility AppCompat

Slide 40

Slide 40 text

EXAMPLE TREATMENT FOR DEVELOPERS Search Google for “Action Bar Style Generator”: Android Action Bar Style Generator by Jeff Gilfelt Style Compatibility AppCompat

Slide 41

Slide 41 text

Blend your visual identity with Holo

Slide 42

Slide 42 text

Checkpoint 2 Worksheet: Checkpoint 2 http://bit.ly/18EhXuo What you will do: •(Generate your own style) •Apply custom theme •Update link color

Slide 43

Slide 43 text

Checkpoint 3: Design - Whitespace and Typography

Slide 44

Slide 44 text

EXAMPLE TREATMENT

Slide 45

Slide 45 text

EXAMPLE TREATMENT Whitespace (Margins + Spacing)

Slide 46

Slide 46 text

EXAMPLE TREATMENT

Slide 47

Slide 47 text

EXAMPLE TREATMENT MORE INFO 48dp high elements: better touch targets, information density

Slide 48

Slide 48 text

EXAMPLE TREATMENT 48dp Pattern MORE INFO 48dp high elements: better touch targets, information density

Slide 49

Slide 49 text

EXAMPLE TREATMENT MORE INFO 48dp high elements: better touch targets, information density

Slide 50

Slide 50 text

80dp 48dp 200dp 8dp 16dp EXAMPLE TREATMENT FOR DEVELOPERS 48dp Rhythm set margins in dimens.xml dimens.xml

Slide 51

Slide 51 text

80dp 48dp 200dp 8dp 16dp EXAMPLE TREATMENT FOR DEVELOPERS 48dp Rhythm set margins in dimens.xml Whitespace (Margins + Spacing) dimens.xml

Slide 52

Slide 52 text

80dp 48dp 200dp 8dp 16dp EXAMPLE TREATMENT FOR DEVELOPERS 48dp Rhythm set margins in dimens.xml Whitespace (Margins + Spacing) dimens.xml

Slide 53

Slide 53 text

80dp 48dp 200dp 8dp 16dp EXAMPLE TREATMENT FOR DEVELOPERS 48dp Rhythm set margins in dimens.xml dimens.xml

Slide 54

Slide 54 text

EXAMPLE TREATMENT

Slide 55

Slide 55 text

EXAMPLE TREATMENT Thumbnail + Photo Treatment

Slide 56

Slide 56 text

EXAMPLE TREATMENT

Slide 57

Slide 57 text

EXAMPLE TREATMENT FOR DEVELOPERS android:scaleType = centerCrop

Slide 58

Slide 58 text

EXAMPLE TREATMENT FOR DEVELOPERS android:scaleType = centerCrop Thumbnail + Photo Treatment

Slide 59

Slide 59 text

EXAMPLE TREATMENT FOR DEVELOPERS android:scaleType = centerCrop Thumbnail + Photo Treatment

Slide 60

Slide 60 text

EXAMPLE TREATMENT FOR DEVELOPERS android:scaleType = centerCrop

Slide 61

Slide 61 text

EXAMPLE TREATMENT Custom Font More spacing Ellipsized text Limited, Fixed number of lines All caps Deemphasized colour for sub headings

Slide 62

Slide 62 text

EXAMPLE TREATMENT Custom Font More spacing Ellipsized text Limited, Fixed number of lines All caps Deemphasized colour for sub headings Typography

Slide 63

Slide 63 text

EXAMPLE TREATMENT Custom Font More spacing Ellipsized text Limited, Fixed number of lines All caps Deemphasized colour for sub headings

Slide 64

Slide 64 text

EXAMPLE TREATMENT FOR DEVELOPERS android:fontFamily = sans-serif-condensed (or -light) android:lineSpacingMultiplier android:textStyle android:ellipsize = end android:maxLines android:singleLine = true android:textAllCaps = true

Slide 65

Slide 65 text

EXAMPLE TREATMENT Typography FOR DEVELOPERS android:fontFamily = sans-serif-condensed (or -light) android:lineSpacingMultiplier android:textStyle android:ellipsize = end android:maxLines android:singleLine = true android:textAllCaps = true

Slide 66

Slide 66 text

EXAMPLE TREATMENT Typography FOR DEVELOPERS android:fontFamily = sans-serif-condensed (or -light) android:lineSpacingMultiplier android:textStyle android:ellipsize = end android:maxLines android:singleLine = true android:textAllCaps = true

Slide 67

Slide 67 text

EXAMPLE TREATMENT FOR DEVELOPERS android:fontFamily = sans-serif-condensed (or -light) android:lineSpacingMultiplier android:textStyle android:ellipsize = end android:maxLines android:singleLine = true android:textAllCaps = true

Slide 68

Slide 68 text

EXAMPLE TREATMENT FOR DEVELOPERS New link color, setting color within TextView

Slide 69

Slide 69 text

EXAMPLE TREATMENT FOR DEVELOPERS New link color, setting color within TextView Custom Highlight + Font

Slide 70

Slide 70 text

EXAMPLE TREATMENT FOR DEVELOPERS New link color, setting color within TextView

Slide 71

Slide 71 text

EXAMPLE TREATMENT FOR DEVELOPERS android:textColorLink = @color/bacon Custom code @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_article_detail, container, false); if (mItem != null) { ((TextView) rootView.findViewById(R.id.article_title)) .setText(mItem.title); // Custom highlight the author ((TextView) rootView.findViewById(R.id.article_byline)) .setText(Html.fromHtml(mItem.time.toUpperCase() + " BY " + mItem.author.toUpperCase() + "")); // Use custom font ((TextView) rootView.findViewById(R.id.article_body)) .setTypeface(Typeface.createFromAsset( getResources().getAssets(), "Rosario-Regular.ttf")); ... } return rootView; }

Slide 72

Slide 72 text

EXAMPLE TREATMENT FOR DEVELOPERS android:textColorLink = @color/bacon Custom code Custom Highlight + Font @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_article_detail, container, false); if (mItem != null) { ((TextView) rootView.findViewById(R.id.article_title)) .setText(mItem.title); // Custom highlight the author ((TextView) rootView.findViewById(R.id.article_byline)) .setText(Html.fromHtml(mItem.time.toUpperCase() + " BY " + mItem.author.toUpperCase() + "")); // Use custom font ((TextView) rootView.findViewById(R.id.article_body)) .setTypeface(Typeface.createFromAsset( getResources().getAssets(), "Rosario-Regular.ttf")); ... } return rootView; }

Slide 73

Slide 73 text

EXAMPLE TREATMENT FOR DEVELOPERS android:textColorLink = @color/bacon Custom code Custom Highlight + Font @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_article_detail, container, false); if (mItem != null) { ((TextView) rootView.findViewById(R.id.article_title)) .setText(mItem.title); // Custom highlight the author ((TextView) rootView.findViewById(R.id.article_byline)) .setText(Html.fromHtml(mItem.time.toUpperCase() + " BY " + mItem.author.toUpperCase() + "")); // Use custom font ((TextView) rootView.findViewById(R.id.article_body)) .setTypeface(Typeface.createFromAsset( getResources().getAssets(), "Rosario-Regular.ttf")); ... } return rootView; }

Slide 74

Slide 74 text

EXAMPLE TREATMENT FOR DEVELOPERS android:textColorLink = @color/bacon Custom code @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_article_detail, container, false); if (mItem != null) { ((TextView) rootView.findViewById(R.id.article_title)) .setText(mItem.title); // Custom highlight the author ((TextView) rootView.findViewById(R.id.article_byline)) .setText(Html.fromHtml(mItem.time.toUpperCase() + " BY " + mItem.author.toUpperCase() + "")); // Use custom font ((TextView) rootView.findViewById(R.id.article_body)) .setTypeface(Typeface.createFromAsset( getResources().getAssets(), "Rosario-Regular.ttf")); ... } return rootView; }

Slide 75

Slide 75 text

Checkpoint 3 Worksheet: Checkpoint 3 http://bit.ly/18EhXuo What you will do: •Update whitespace (padding and margins) •Fix image thumbnails and photos •Update Typography •Custom highlighting and font

Slide 76

Slide 76 text

Checkpoint 4: Tablet UI

Slide 77

Slide 77 text

EXAMPLE TREATMENT FOR DEVELOPERS Guides: “Designing for Multiple Screens” and “Building a Dynamic UI with Fragments”

Slide 78

Slide 78 text

EXAMPLE TREATMENT FOR DEVELOPERS Guides: “Designing for Multiple Screens” and “Building a Dynamic UI with Fragments” Two-pane UI

Slide 79

Slide 79 text

EXAMPLE TREATMENT FOR DEVELOPERS Guides: “Designing for Multiple Screens” and “Building a Dynamic UI with Fragments”

Slide 80

Slide 80 text

EXAMPLE TREATMENT FOR DEVELOPERS Landscape tablet resources: values-sw600dp-land Reusable references: refs.xml @layout/activity_article_twopane refs.xml

Slide 81

Slide 81 text

EXAMPLE TREATMENT FOR DEVELOPERS Landscape tablet resources: values-sw600dp-land Reusable references: refs.xml Two-pane UI @layout/activity_article_twopane refs.xml

Slide 82

Slide 82 text

EXAMPLE TREATMENT FOR DEVELOPERS Landscape tablet resources: values-sw600dp-land Reusable references: refs.xml @layout/activity_article_twopane refs.xml

Slide 83

Slide 83 text

EXAMPLE TREATMENT

Slide 84

Slide 84 text

EXAMPLE TREATMENT Two-pane UI with better spacing

Slide 85

Slide 85 text

EXAMPLE TREATMENT Two-pane UI with better spacing

Slide 86

Slide 86 text

EXAMPLE TREATMENT

Slide 87

Slide 87 text

EXAMPLE TREATMENT 96dp 400dp 16dp 80dp dimens.xml FOR DEVELOPERS Landscape tablet resources: values-sw600dp-land Tablet-specific dimensions: dimens.xml

Slide 88

Slide 88 text

EXAMPLE TREATMENT Two-pane UI with better spacing 96dp 400dp 16dp 80dp dimens.xml FOR DEVELOPERS Landscape tablet resources: values-sw600dp-land Tablet-specific dimensions: dimens.xml

Slide 89

Slide 89 text

EXAMPLE TREATMENT Two-pane UI with better spacing 96dp 400dp 16dp 80dp dimens.xml FOR DEVELOPERS Landscape tablet resources: values-sw600dp-land Tablet-specific dimensions: dimens.xml

Slide 90

Slide 90 text

EXAMPLE TREATMENT 96dp 400dp 16dp 80dp dimens.xml FOR DEVELOPERS Landscape tablet resources: values-sw600dp-land Tablet-specific dimensions: dimens.xml

Slide 91

Slide 91 text

Checkpoint 4 Worksheet: Checkpoint 4 http://bit.ly/18EhXuo What you will do: •Add tablet layout •Tablet-optimized whitespace

Slide 92

Slide 92 text

Checkpoint 5: Bitmap Performance

Slide 93

Slide 93 text

EXAMPLE TREATMENT PROBLEM: OutOfMemoryException on low-end devices

Slide 94

Slide 94 text

EXAMPLE TREATMENT PROBLEM: OutOfMemoryException on low-end devices Bitmap Performance Tuning

Slide 95

Slide 95 text

EXAMPLE TREATMENT PROBLEM: OutOfMemoryException on low-end devices

Slide 96

Slide 96 text

EXAMPLE TREATMENT FOR DEVELOPERS BitmapFactory.Options: options.inSampleSize = 16 (or use smaller images) @Override public View getView(int position, View convertView, ViewGroup container) { if (convertView == null) { convertView = LayoutInflater.from(getActivity()) .inflate(R.layout.list_item_article, container, false); } ... BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; Bitmap b = BitmapFactory.decodeResource(getResources(), item.photoResId, options); ((ImageView) convertView.findViewById(R.id.thumbnail)).setImageBitmap(b); return convertView; }

Slide 97

Slide 97 text

EXAMPLE TREATMENT FOR DEVELOPERS BitmapFactory.Options: options.inSampleSize = 16 (or use smaller images) Bitmap Performance Tuning @Override public View getView(int position, View convertView, ViewGroup container) { if (convertView == null) { convertView = LayoutInflater.from(getActivity()) .inflate(R.layout.list_item_article, container, false); } ... BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; Bitmap b = BitmapFactory.decodeResource(getResources(), item.photoResId, options); ((ImageView) convertView.findViewById(R.id.thumbnail)).setImageBitmap(b); return convertView; }

Slide 98

Slide 98 text

EXAMPLE TREATMENT FOR DEVELOPERS BitmapFactory.Options: options.inSampleSize = 16 (or use smaller images) Bitmap Performance Tuning @Override public View getView(int position, View convertView, ViewGroup container) { if (convertView == null) { convertView = LayoutInflater.from(getActivity()) .inflate(R.layout.list_item_article, container, false); } ... BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; Bitmap b = BitmapFactory.decodeResource(getResources(), item.photoResId, options); ((ImageView) convertView.findViewById(R.id.thumbnail)).setImageBitmap(b); return convertView; }

Slide 99

Slide 99 text

EXAMPLE TREATMENT FOR DEVELOPERS BitmapFactory.Options: options.inSampleSize = 16 (or use smaller images) @Override public View getView(int position, View convertView, ViewGroup container) { if (convertView == null) { convertView = LayoutInflater.from(getActivity()) .inflate(R.layout.list_item_article, container, false); } ... BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; Bitmap b = BitmapFactory.decodeResource(getResources(), item.photoResId, options); ((ImageView) convertView.findViewById(R.id.thumbnail)).setImageBitmap(b); return convertView; }

Slide 100

Slide 100 text

EXAMPLE TREATMENT

Slide 101

Slide 101 text

EXAMPLE TREATMENT Dynamically calculate inSampleSize

Slide 102

Slide 102 text

EXAMPLE TREATMENT

Slide 103

Slide 103 text

EXAMPLE TREATMENT FOR DEVELOPERS options.inJustDecodeBounds = true; options.inSampleSize = 16 (or use smaller images) public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); }

Slide 104

Slide 104 text

EXAMPLE TREATMENT FOR DEVELOPERS options.inJustDecodeBounds = true; options.inSampleSize = 16 (or use smaller images) Dynamically calculate inSampleSize public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); }

Slide 105

Slide 105 text

EXAMPLE TREATMENT FOR DEVELOPERS options.inJustDecodeBounds = true; options.inSampleSize = 16 (or use smaller images) Dynamically calculate inSampleSize public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); }

Slide 106

Slide 106 text

EXAMPLE TREATMENT FOR DEVELOPERS options.inJustDecodeBounds = true; options.inSampleSize = 16 (or use smaller images) public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); }

Slide 107

Slide 107 text

EXAMPLE TREATMENT FOR DEVELOPERS calculate optimal sample size for required size public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 16; if (reqWidth == 0 || reqHeight == 0) return inSampleSize; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; }

Slide 108

Slide 108 text

EXAMPLE TREATMENT FOR DEVELOPERS calculate optimal sample size for required size Dynamically calculate inSampleSize public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 16; if (reqWidth == 0 || reqHeight == 0) return inSampleSize; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; }

Slide 109

Slide 109 text

EXAMPLE TREATMENT FOR DEVELOPERS calculate optimal sample size for required size public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 16; if (reqWidth == 0 || reqHeight == 0) return inSampleSize; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; }

Slide 110

Slide 110 text

Checkpoint 5 Worksheet: Checkpoint 5 http://bit.ly/18EhXuo What you will do: •Load bitmaps using ‘sampleSize’ •Set ‘inJustDecodeBounds’ parameter

Slide 111

Slide 111 text

Checkpoint 6: Image Loading in Background Thread

Slide 112

Slide 112 text

EXAMPLE TREATMENT Slow Fast

Slide 113

Slide 113 text

EXAMPLE TREATMENT Load images concurrently off the Main(UI) Thread Slow Fast

Slide 114

Slide 114 text

EXAMPLE TREATMENT Slow Fast

Slide 115

Slide 115 text

EXAMPLE TREATMENT FOR DEVELOPERS AsyncTask class BitmapWorkerTask extends AsyncTask { private final WeakReference imageViewReference; private int resId = 0; public BitmapWorkerTask(ImageView imageView) { // Use a WeakReference to ensure the ImageView can // be garbage collected imageViewReference = new WeakReference(imageView); } // Decode image in background. @Override protected Bitmap doInBackground(Integer... params) { resId = params[0]; ImageView thumbnail = imageViewReference.get(); Bitmap bitmap = decodeSampledBitmapFromResource( getResources(), resId, thumbnail.getWidth(), thumbnail.getHeight()); addBitmapToMemoryCache(String.valueOf(params[0]), bitmap); return bitmap; } ...

Slide 116

Slide 116 text

EXAMPLE TREATMENT FOR DEVELOPERS AsyncTask Load images concurrently off the Main(UI) Thread class BitmapWorkerTask extends AsyncTask { private final WeakReference imageViewReference; private int resId = 0; public BitmapWorkerTask(ImageView imageView) { // Use a WeakReference to ensure the ImageView can // be garbage collected imageViewReference = new WeakReference(imageView); } // Decode image in background. @Override protected Bitmap doInBackground(Integer... params) { resId = params[0]; ImageView thumbnail = imageViewReference.get(); Bitmap bitmap = decodeSampledBitmapFromResource( getResources(), resId, thumbnail.getWidth(), thumbnail.getHeight()); addBitmapToMemoryCache(String.valueOf(params[0]), bitmap); return bitmap; } ...

Slide 117

Slide 117 text

EXAMPLE TREATMENT FOR DEVELOPERS AsyncTask Load images concurrently off the Main(UI) Thread class BitmapWorkerTask extends AsyncTask { private final WeakReference imageViewReference; private int resId = 0; public BitmapWorkerTask(ImageView imageView) { // Use a WeakReference to ensure the ImageView can // be garbage collected imageViewReference = new WeakReference(imageView); } // Decode image in background. @Override protected Bitmap doInBackground(Integer... params) { resId = params[0]; ImageView thumbnail = imageViewReference.get(); Bitmap bitmap = decodeSampledBitmapFromResource( getResources(), resId, thumbnail.getWidth(), thumbnail.getHeight()); addBitmapToMemoryCache(String.valueOf(params[0]), bitmap); return bitmap; } ...

Slide 118

Slide 118 text

EXAMPLE TREATMENT FOR DEVELOPERS AsyncTask class BitmapWorkerTask extends AsyncTask { private final WeakReference imageViewReference; private int resId = 0; public BitmapWorkerTask(ImageView imageView) { // Use a WeakReference to ensure the ImageView can // be garbage collected imageViewReference = new WeakReference(imageView); } // Decode image in background. @Override protected Bitmap doInBackground(Integer... params) { resId = params[0]; ImageView thumbnail = imageViewReference.get(); Bitmap bitmap = decodeSampledBitmapFromResource( getResources(), resId, thumbnail.getWidth(), thumbnail.getHeight()); addBitmapToMemoryCache(String.valueOf(params[0]), bitmap); return bitmap; } ...

Slide 119

Slide 119 text

EXAMPLE TREATMENT FOR DEVELOPERS AsyncTask ... // Once complete, see if ImageView is still around and set bitmap. @Override protected void onPostExecute(Bitmap bitmap) { if (isCancelled()) { bitmap = null; } if (imageViewReference != null && bitmap != null) { final ImageView imageView = imageViewReference.get(); final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); if (this == bitmapWorkerTask && imageView != null) { imageView.setImageBitmap(bitmap); } } } }

Slide 120

Slide 120 text

EXAMPLE TREATMENT FOR DEVELOPERS AsyncTask Load images concurrently off the Main(UI) Thread ... // Once complete, see if ImageView is still around and set bitmap. @Override protected void onPostExecute(Bitmap bitmap) { if (isCancelled()) { bitmap = null; } if (imageViewReference != null && bitmap != null) { final ImageView imageView = imageViewReference.get(); final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); if (this == bitmapWorkerTask && imageView != null) { imageView.setImageBitmap(bitmap); } } } }

Slide 121

Slide 121 text

EXAMPLE TREATMENT FOR DEVELOPERS AsyncTask ... // Once complete, see if ImageView is still around and set bitmap. @Override protected void onPostExecute(Bitmap bitmap) { if (isCancelled()) { bitmap = null; } if (imageViewReference != null && bitmap != null) { final ImageView imageView = imageViewReference.get(); final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); if (this == bitmapWorkerTask && imageView != null) { imageView.setImageBitmap(bitmap); } } } }

Slide 122

Slide 122 text

Checkpoint 6 Worksheet: Checkpoint 6 http://bit.ly/18EhXuo What you will do: •Add AsyncTask for loading images

Slide 123

Slide 123 text

Checkpoint 6: Image Cache

Slide 124

Slide 124 text

EXAMPLE TREATMENT Faster Fast

Slide 125

Slide 125 text

EXAMPLE TREATMENT Use Image Cache Faster Fast

Slide 126

Slide 126 text

EXAMPLE TREATMENT Faster Fast

Slide 127

Slide 127 text

EXAMPLE TREATMENT FOR DEVELOPERS LruCache private LruCache mMemoryCache; // Instantiate in the onCreate() method public void addBitmapToMemoryCache(String key, Bitmap bitmap) { if (getBitmapFromMemCache(key) == null) { mMemoryCache.put(key, bitmap); } } public Bitmap getBitmapFromMemCache(String key) { return mMemoryCache.get(key); }

Slide 128

Slide 128 text

EXAMPLE TREATMENT FOR DEVELOPERS LruCache Use Image Cache private LruCache mMemoryCache; // Instantiate in the onCreate() method public void addBitmapToMemoryCache(String key, Bitmap bitmap) { if (getBitmapFromMemCache(key) == null) { mMemoryCache.put(key, bitmap); } } public Bitmap getBitmapFromMemCache(String key) { return mMemoryCache.get(key); }

Slide 129

Slide 129 text

EXAMPLE TREATMENT FOR DEVELOPERS LruCache Use Image Cache private LruCache mMemoryCache; // Instantiate in the onCreate() method public void addBitmapToMemoryCache(String key, Bitmap bitmap) { if (getBitmapFromMemCache(key) == null) { mMemoryCache.put(key, bitmap); } } public Bitmap getBitmapFromMemCache(String key) { return mMemoryCache.get(key); }

Slide 130

Slide 130 text

EXAMPLE TREATMENT FOR DEVELOPERS LruCache private LruCache mMemoryCache; // Instantiate in the onCreate() method public void addBitmapToMemoryCache(String key, Bitmap bitmap) { if (getBitmapFromMemCache(key) == null) { mMemoryCache.put(key, bitmap); } } public Bitmap getBitmapFromMemCache(String key) { return mMemoryCache.get(key); }

Slide 131

Slide 131 text

EXAMPLE TREATMENT FOR DEVELOPERS LruCache calculate cache size in sizeOf(..) // Get max available VM memory in kilobytes, exceeding this amount // will throw an OutOfMemory exception. final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache. final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache(cacheSize) { @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) @Override protected int sizeOf(String key, Bitmap bitmap) { // The cache size in kilobytes rather than if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1) { return bitmap.getByteCount() / 1024; } else { return bitmap.getRowBytes() * bitmap.getHeight() / 1024; } } };

Slide 132

Slide 132 text

EXAMPLE TREATMENT FOR DEVELOPERS LruCache calculate cache size in sizeOf(..) Use Image Cache // Get max available VM memory in kilobytes, exceeding this amount // will throw an OutOfMemory exception. final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache. final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache(cacheSize) { @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) @Override protected int sizeOf(String key, Bitmap bitmap) { // The cache size in kilobytes rather than if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1) { return bitmap.getByteCount() / 1024; } else { return bitmap.getRowBytes() * bitmap.getHeight() / 1024; } } };

Slide 133

Slide 133 text

EXAMPLE TREATMENT FOR DEVELOPERS LruCache calculate cache size in sizeOf(..) Use Image Cache // Get max available VM memory in kilobytes, exceeding this amount // will throw an OutOfMemory exception. final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache. final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache(cacheSize) { @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) @Override protected int sizeOf(String key, Bitmap bitmap) { // The cache size in kilobytes rather than if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1) { return bitmap.getByteCount() / 1024; } else { return bitmap.getRowBytes() * bitmap.getHeight() / 1024; } } };

Slide 134

Slide 134 text

EXAMPLE TREATMENT FOR DEVELOPERS LruCache calculate cache size in sizeOf(..) // Get max available VM memory in kilobytes, exceeding this amount // will throw an OutOfMemory exception. final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache. final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache(cacheSize) { @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) @Override protected int sizeOf(String key, Bitmap bitmap) { // The cache size in kilobytes rather than if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1) { return bitmap.getByteCount() / 1024; } else { return bitmap.getRowBytes() * bitmap.getHeight() / 1024; } } };

Slide 135

Slide 135 text

Checkpoint 6 Worksheet: Checkpoint 6 http://bit.ly/18EhXuo What you will do: •Add LruCache to cache images Faster

Slide 136

Slide 136 text

Final: XYZReader

Slide 137

Slide 137 text

EXAMPLE TREATMENT

Slide 138

Slide 138 text

Thank you! A few simple techniques: Backwards Compatibility using Support Library Design, Spacing, Typography Improve app performance Interested to find out more? developer.android.com +Android Developers

Slide 139

Slide 139 text

+Yuichi Araki +Jan-Felix Schmakeit Thank you! http://plus.google.com/+AndroidDevelopers http://developer.android.com