Upgrade to Pro — share decks privately, control downloads, hide ads and more …

GDG - Android UI Fundamentals

GDG - Android UI Fundamentals

GDG - Android Athens: In this talk we will explore the Constraint Layout component alongside with the Android Studio UI Builder, to easily compose a responsive user interface from scratch. Moreover, we will cover basic UI testing using the new Android Studio tool named Espresso Test Recorder, to automatically generate UI test cases. Finally, we will discuss about the Google Android Associate Certification and preparation tips to get officially certified!

Panagiotis Vasileiou

June 07, 2017
Tweet

More Decks by Panagiotis Vasileiou

Other Decks in Programming

Transcript

  1. Android UI Fundamentals Panagiotis Vasileiou, Lead Software Engineer @ GNT

    S.A. panosvas GDG Android Athens The Cube, 7 June, 2017
  2. Let's Start!  What is a UI?  Easy one...

    It is what you see! Hm... or maybe not?  Well, Android UI hides a lot of magic behind the scenes.  How to build a UI? 1. Declare UI elements in XML or 2. Programmatically construct layout elements at runtime  What to choose?  In general, prefer the XML declarations for predefined user interfaces  More scalable, testable, flexible (multiple screens, languages, …)
  3. UI Overview using XML Layouts  What is this XML?

     It is a quite human readable representation of the UI  Consists of ViewGroups and Views 1. View: Rectangular area in screen for drawing and event handling 2. ViewGroup: Layouts, also known as invisible containers for Views or other ViewGroups  Has only one root element  Builds a View hierarchy (like a tree) to consist the UI  It is compiled into a View Resource  It can be loaded from your application code: setContentView(R.my_awesome_layout);
  4. XML Example ViewGroup View View <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textSize="21sp" android:textStyle="bold" android:text="Do not hardcode me here!"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Neither me!"/> </LinearLayout>
  5. XML XML XML XML XML XML XML XML  Do

    I have to manually generate all XML?  If you want, you can do it!  However, there is a drag n drop design tool in Android Studio  Oh, I remember (nightmares)…  Indeed, there are some issues with this tool  Pros  Easily find available UI components  Drag n drop, which automatically generates the XML staff  Cons  Difficult for components alignment
  6. XML? Hm...  So, any alternative?  On May 2016,

    Google released the alpha-1 of ConstraintLayout  ConstraintLayout makes it feasible to build flat view hierarchy instead of nested Views  Similarities with RelativeLayout (relationships between views) but more powerful  Android Studio Layout Editor is built especially for ConstraintLayout, so, you can simply drag n drop to create the whole UI  Compatibility with Android 2.3 (API level 9) and higher  Bundled as separate library (due to continuous development and updates)
  7. Now, Use it...  How to install it?  Go

    to SDK Manager  Go to SDK Tools  Under Support Repository  Mark ConstraintLayout and Solver  How to use it?  Under module build.gradle add the following dependency: compile 'com.android.support.constraint:constraint-layout:1.0.2'
  8. ConstraintLayout  Any details?  The main concept is the

    Constraint  Each Constraint represents a connection or alignment to another view, parent layout, or invisible guideline  Constraint can define both vertical and horizontal axis position  Minimum one constraint for each axis  A view with no constraints is placed at the top-left corner [0,0]  Layout Editor warns us about missing constraints Horizontal Alignment Vertical Alignment Baseline Alignment
  9. More Details  3 Possible Adjustments  Wrap Content 

    Match Constraints (0dp)  Fixed  Able to set:  Set Margins  Set Ratio (width : height)
  10. More Hints  What else?  Relative Positioning  Horizontal:

    left, right, start, end  Vertical: bottom, up and baseline (align texts)  Margins  Visibility Behavior  GONE Views are taken into account in constraint calculations with zero dimensions, so, nothing is broken  Bias  Tweak the position to one side over the other V V No bias: opposite forces place the view at the middle Left bias 20%: app:layout_constraintHorizontal_bias="0.2"
  11. More...  Chain Heads  Chain of widgets  Select

    all the desired widgets -> right click -> center horizontally or vertically  You can align top or bottom edges (left or right for vertical)  Left or top most widget is the head  Various styles of chain
  12. Example  Horizontal Guideline  Position at 40% from top

     Main ImageView  All edges "Match Constraint"  Star ImageView  One option is to have one alignment as "Match Constraint" and the other as "Wrap Content" in case of two connectors  CalendarView  All edges (Match Constraint)
  13. <ImageView android:id="@+id/mainImage" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginBottom="16dp" android:layout_marginTop="0dp" android:contentDescription="@string/main_image" android:scaleType="centerCrop" app:layout_constraintBottom_toTopOf="@+id/guideline" app:layout_constraintHorizontal_bias="0.0"

    app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.0" app:srcCompat="@drawable/bg1" /> <ImageView android:id="@+id/starImage" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginBottom="2dp" android:layout_marginEnd="25dp" android:contentDescription="@string/favorite_img" app:layout_constraintBottom_toTopOf="@+id/guideline" app:layout_constraintRight_toRightOf="parent" app:srcCompat="@android:drawable/btn_star_big_on" /> <CalendarView android:id="@+id/calendarView" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" android:layout_marginTop="8dp" app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="8dp" app:layout_constraintVertical_bias="0.0" app:layout_constraintTop_toTopOf="@+id/guideline" /> <android.support.constraint.Guideline android:id="@+id/guideline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.4" /> 3.7'' Nexus 1 5'' Pixel 7'' Nexus 7 10'' Nexus 10 320x290 – Watch (Round Chin)  Position does not break, however:  There is always room for improvement (check size of star)  Learn about Constraints measurement process (see refs)  You can always create new layouts variants  Enrich and Debug your layout e.g.:  Theme Editor  Hierarchy Viewer  GPU Overdraw tool  Layout Inspector
  14. Let's Test it!  You are not kidding, right? 

    Nope! No worries, take an espresso!
  15. Espresso UI Testing  Any details?  As developers we

    want to prevent situations of unexpected behaviors of the app  We need to be confident (at least in high percentage) that the UI is working properly  Espresso testing provides the tools to test the UI  It is provided by the Android Testing Support Library  Runs on Android 2.3.3 (API level 10) and greater  Automatically detects an idle UI thread, providing accurate results  Instrumentation-based API running with AndroidJUnitRunner
  16. Espresso UI Testing  Setup  Inside the build.gradle, add

    the dependency: androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' })  Setup the test runner under defaultConfig: testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"  Disable device animations under the developer options:  Window Animation Scale  Animator Duration Scale  Simulate Secondary Displays
  17. Espresso UI Basics  How is this working?  Espresso:

    the entry point  ViewMatchers: finding specific views  ViewActions: interact with the view  ViewAssertions: validate the desired properties of the view onView(withId(R.id.my_view)) // withId(R.id.my_view) is a ViewMatcher .perform(click()) // click() is a ViewAction .check(matches(isDisplayed())); // matches(isDisplayed()) is a ViewAssertion
  18. Codeless UI Testing...  How much code do I have

    to write?  Hm... If you want, you can write no code  A stable version of Espresso Test Recorder added in Android Studio 2.3  Record a whole test scenario  Record interactions  Add assertions to View properties  Auto-generated Espresso UI test code  Automatically resolves project dependencies for Espresso UI testing
  19. Espresso Test Recorder  Any Instructions?  Of course, after

    creating a UI go to:  Run > Record Espresso Test  Select the target device  Espresso test recorder will automatically build your project and install as well as run it on the target device  Do not force close the dialog saying waiting for the debugger (or attaching debugger) 1 2
  20. Espresso Test Recorder  Make Interactions and Assertions  Interact

    with the App  When you are done click "Add Assertion"  Espresso Test Recorder is dumping the current UI  Add the assertions of the View's properties  Available assertions from Test recorder:  Text is  Exists  Does not Exists  Click "OK" and pickup a self explanatory name for your test case 3
  21. Espresso Test Recorder Sample  What is the output? @Test

    public void mainActivityTestNameReplace() { ViewInteraction appCompatEditText = onView( allOf(withId(R.id.editText4), withText("Name"), isDisplayed())); appCompatEditText.perform(click()); ViewInteraction appCompatEditText2 = onView( allOf(withId(R.id.editText4), withText("Name"), isDisplayed())); appCompatEditText2.perform(replaceText("Nice")); ViewInteraction appCompatEditText3 = onView( allOf(withId(R.id.editText4), withText("Nice"), isDisplayed())); appCompatEditText3.perform(pressImeActionButton()); ViewInteraction editText = onView( allOf(withId(R.id.editText4), withText("Nice"), childAtPosition(childAtPosition( withId(android.R.id.content),0),0),isDisplayed())); editText.check(matches(withText("Nice"))); } 1 2 3 4 4 3 2 1
  22. Android Studio Run Tests  How to run the tests?

     Run each test explicitly or all together  Simply right click and run it!  Check the results in Android Studio console  Or export them in html, xml or custom xsl
  23. Firebase Test Lab  How many devices do I need

    to test?  Good question! As many as you can...  For that reason the Firebase Test Lab is there for you  Test on real devices  Test even if you have no test cases, with Robo tests  Workflow Integration (CI)  Free 10 tests per day for virtual devices  Free 5 tests per day for real devices
  24. Firebase Test Lab  How to integrate with Firebase Test

    Lab?  In Android Studio there is a Firebase assistant which guides you through all the firebase components  Go to Tools > Firebase and the choose the Test Lab  Many of the steps are performed automatically from the Android Studio (with your permission)  In manual configurations there are detailed information to guide you
  25. Wow! Perfect! Or not?...  It is perfect!  No,

    it is not :P  First of all only a few assertions are available through the test recorder  Further assertions have to be implemented inside the Espresso test code  Code will be also required to deal with any kind of delays, such as async tasks
  26. Perfection, not!  Anything else?  There are still some

    bugs in the recorder (e.g. different issues with real devices, device locale)  Moreover, there are some issues with the soft keyboard and the emulator  There will be times where we need to correct the code  It is possible that the recorder will generate for a keyboard "Done" command, one redundant command  In the following example the keyboard never closed (instead the done was pressed), so the press ime action button failed... appCompatEditText2.perform(replaceText("Nice"), closeSoftKeyboard()); ViewInteraction appCompatEditText3 = onView( allOf(withId(R.id.editText4), withText("Nice"), isDisplayed())); appCompatEditText3.perform(pressImeActionButton());
  27. Nice Tools  Not perfect, but both ConstraintLayout and Espresso

    Test Recorder are cool, aren't they?  Of course they are!  ConstraintLayout allows you to easily build dynamic and flat views  Moreover, let's you easily extend the view for multiple variants (landscape, tablet, etc)  Espresso test recorder is a great way to build a simple test suite when you have nothing  Moreover, is a great chance to learn the Espresso UI API and build some awesome tests, to prevent difficult situations :)
  28. Expand your Knowledge!  Any other Tools?  New features

    are coming day to day  It is crucial to have strong foundations  Stay up to date!  Any Guidelines?  Deep learn new things and foundations  Get some first class trainings  Prove your knowledge with certifications  Google gives a certification for Android Associate Developers
  29. Get Certified!  What is about?  Google certifies that

    you have all the skills and competences to build a career as an entry-level Android developer  For a junior developer the certification demands some practice and study, as it examines many core Android functions  What it covers?  Testing and Debugging (write tests, use developer tools, debug, find crashes, layout errors, memory leaks)  Application User Interface (UI) and User Experience (UX) (create new or modify layouts both in XML and Java)  Fundamental Application Components (Activity, Service, Broadcast Receiver, Content Provider)  Persistent Data Storage (file, preferences, databases)  Enhanced System Integration (app notifications and widgets)
  30. Android Associate Developer  What if I don't know all

    of them?  No worries! Google in partnership with Udacity, created a couple of Training programs for Android:  Android Junior Nanodegree  Associate Android Developer Fast Track (designed especially for the Certification)  Android Nanodegree (more advanced which includes a challenging capstone project)  What is the cost?  By the time of this presentation:  Google Certification costs $149  Associate Android Developer Fast Track program costs $750 (includes certification fees)
  31. Android Associate Developer  What's the process?  Exam 

    You will get a starter project and 48 hours to solve some issues!  You will fix bugs, improve layouts, add features  The evaluation is Performance based  Exit Interview  If you pass the exam there is an exit interview  Explain how did you solve the problems  Proof of your identity  If I fail?  Don't worry, there is a 2nd attempt whenever you want for free  3rd attempt after 2 months for free  and in case of fail again, you should wait 6 months and then pay again
  32. Resources  Sample Project: https://github.com/panosvas/UI-Fundamentals  ConstraintLayout  Overview: https://developer.android.com/training/constraint-layout/index.html

     Details: https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html  Constraints Measurement Process: http://wiresareobsolete.com/2016/07/constraintlayout-part-2/  Android Studio Editor: https://developer.android.com/studio/write/layout-editor.html  Espresso UI  Espresso UI basics: https://developer.android.com/training/testing/ui-testing/espresso-testing.html  Espresso Test Recorder: https://developer.android.com/studio/test/espresso-test-recorder.html  Android Associate Developer Certification  Official Google: https://developers.google.com/training/certification/  Udacity + Google: https://www.udacity.com/google-certifications  Udacity Fast Track: https://www.udacity.com/course/associate-android-developer-fast-track--nd818
  33. THANK YOU! GDG Android Athens The Cube, 7 June, 2017

    We are hiring! Join the team! Panagiotis Vasileiou Lead Software Engineer @panosvas Contact us: [email protected]