Author: Suleiman

  • Framer X For Design – 5 Reasons Why I Switched

    Framer X For Design – 5 Reasons Why I Switched

    As a developer turned designer, I have always been fascinated with ways to close the gap between design and development. Recently, I stumbled upon Framer X. After using it for quite a while, I’m convinced that it is a powerful new design tool that closes that gap considerably and encourages tighter collaboration.

    (more…)
  • Build your UX Portfolio from Scratch – Choosing a Web Stack

    Build your UX Portfolio from Scratch – Choosing a Web Stack

    Choosing to hand-code your UX portfolio can be an ambitious, yet daunting task. Your portfolio website is perhaps the most important avenue to display your experience, skills, and values as a designer.

    With that said, you want to put your best foot forward. Having complete control in how you do this is what development (hand-coding) can offer albeit at the cost of time and increased effort.

    A majority of that time could go into choosing the right set of tools for web development. Especially, when there’s a multitude of options to choose from that do similar things. It is important to choose tools that are not only easy to understand but speed up our workflow. 

    Even then, making a choice and then sticking with it can be hard, especially when you discover a blocker later down the road.

    That’s what I’m here to help you with.

    (more…)
  • Build your UX Portfolio From Scratch – Design

    Build your UX Portfolio From Scratch – Design

    Designing your own UX portfolio can give you an edge to stand out from the crowd. By choosing to design it yourself, it is an opportunity to showcase your brand and who you are.

    By being original and unique, your portfolio will be memorable. So don’t copy a theme or someone else’s design. You don’t want your UX portfolio to come off as a common template or worse, a rip-off.

    (more…)
  • Build your UX Portfolio From Scratch – Getting Started

    Build your UX Portfolio From Scratch – Getting Started

    Our UX portfolio is a key piece of displaying our capabilities as a designer. Hence, it becomes essential to make one that can speak for you.

    In this tutorial series, I will walk you through how I designed and developed my UX portfolio website. Sure, I could’ve named this article as ‘How I Built My Portfolio’ but I want to show you how YOU can do it too. It’s easy, and you don’t need to be a developer. Let me show you.

    (more…)
  • Android Pagination Tutorial – Adding Swipe-to-Refresh

    Android Pagination Tutorial – Adding Swipe-to-Refresh

    Pagination allows loading a long list of data in chunks. You see this in action in news feeds in social media apps, otherwise known as endless or infinite scrolling. In this tutorial, I will specifically show you how to handle pagination with Swipe-to-Refresh involved.

    (more…)
  • How To Design A Great Mobile App Intro By Learning From The Best

    How To Design A Great Mobile App Intro By Learning From The Best

    The App Intro or Product Tour is an introductory welcome experience for first-time users to your product. In this article, we will look at how to design great app intros by learning from the best mobile apps.

    (more…)

  • Android Pagination Tutorial—Handling Multiple View Types

    Android Pagination Tutorial—Handling Multiple View Types

    Pagination is also known as endless or infinite scrolling. This is achieved using RecyclerView. In this tutorial, I’ll show you how to paginate when multiple View Types are involved.

    (more…)
  • Use Empty States to your Advantage – Better User Retention

    Use Empty States to your Advantage – Better User Retention

    Empty States are often neglected and designed last. I don’t blame you though. After all, compared to the main screens, these aren’t important. Right?

    Sadly, no. The worst that can happen is that users can uninstall your app after first use. Trust me, you don’t want that to happen.

    Users who uninstall your app after first-use are most likely to never return.

    Mostly, empty state screens are ignored until the app is done. Then, you realize that a particular screen could be empty at some time. So you just throw in a little error message like this and call it a day.

    iOS Pages app — I’m not sure where it’s asking me to tap…

    This is NOT okay! Once users reach an empty state screen, they might not know what to do. Or they simply might move on to another screen, or worse, another app.

    The gravity of the situation is worse than you think! Here’s a wake-up call.

    The average app mostly loses its entire user base within a few months. – Andrew Chen (Growth at Uber, LinkedIn Influencer)

    First, let’s clarify what an empty state is. Then, we’ll see why it must be given importance. Next, let’s find out when it can occur and how to tackle them. Finally, we’ll see how to design effective Empty States.


    What are Empty States?

    I’ll spare you the boring book definition here.

    Empty State or zero-data state is what a user sees when there is no data to display on-screen.

    Image credit: emptystat.es

    Why Bother?

    We need to make sure that users learn the purpose of a particular screen. If it’s a news app, and there is no news to display, tell them why.

    Well, that might sound ironic. But what if the network call fails?

    The reality is that 77% of users will uninstall your app in 3 days. Only the top 10-50 apps are able to break that and keep more users.

    You might say these are extreme statistics but think again.

    The difficulty of User Retention

    Let me put that in perspective for you.

    You use apps too right? Say you want to try out a news app. I’m sure you don’t download just one, but at least a couple of them.

    Then, you give each app a try. You try to see which one is good. Finally, you keep what you like and you uninstall the rest.

    Users try out a lot of apps but decide which ones they want to ‘stop using’ within the first 3-7 days – Ankit Jain, Google.

    Get it? That might happen to your app as well. Hence you need to use everything at your disposal to keep your users.

    Once they start using your app, do your best to make them stay. Empty States are the perfect opportunity to do so.

    Use them to encourage interaction, reinforce your brand and increase user loyalty. I know such terms might sound cheesy. But if you use Empty States correctly, your app adoption rates will be much higher. In other words, that translates to lesser app uninstalls.

    The best way to bend the retention curve is to target the first few days of usage, and in particular the first visit – Andrew Chen

    When are most of the empty states visible? During the first few days of using the app.

    Now you know what needs to be done. Let’s see when Empty States can occur and how to best design them.

    Another user retention techniqueUsing Skeleton Screens make your app appear faster.


    When can Empty States occur?

    Now that we know about Empty States and its importance, let’s see when it can actually occur.

    To put it simply, it occurs whenever there is an absence of data.

    Yes, that’s just straight from the definition, but the exact scenarios are as follows:

    1. for first-time users
    2. when an error occurs

    1. For first-time users

    Empty States can serve as an onboarding for first-time users. Yes, you don’t have to do those forced carousel-like product tours!

    Let’s take the example of the Google Keep Android app. It handles Empty States for first-time users in a unique way.

    Google Keep — Empty State

    It displays ‘starter content’ to familiar users with its app. Typically, when you open a note-taking app, it will be empty. You don’t know how a bunch of notes will appear on-screen. You’ll have to create a couple of them to find out.

    Instead, Google Keep does that for you. So although you don’t have any notes, Keep creates a few.

    With this, first-time users are educated on 2 things:

    1. how notes work within the app
    2. learn about the app’s features

    That’s pretty smart, right? It works extremely well for them. We’ll talk more about ‘starter content’ later into this article.

    For apps like notes, email, bookmark managers and others, there is no content, to begin with! Users will have to start adding content manually to populate them. In such apps, having Empty States for first-time users is a sure shot.

    But keep in mind that you have to think about individual screens rather than the entire app.

    For example, a news app might show worldwide news by default on the home screen. So no worries there. Say the news app allows a bookmark feature. That screen would be empty unless users bookmark a news article. So that’s an Empty State too. How would you handle that? Think about it!

    2. When an error occurs…

    Now for some apps, even if you’re a new user, there will be some content to display. Say that the app makes an API call to fetch content, and for some reason, it fails.

    When a new user opens your app and goes to the home screen, you don’t want that to happen. It appears very bad. Don’t show a generic error message.

    Safari iOS app — No internet state Image credit: tympanus.net

    That is just one scenario. This could happen to ANY screen. Make sure you handle that as well.

    Tell users why it failed

    This is perhaps the most important thing to remember. When you’re showing an Empty State in the event of an error, tell users what happened.

    Make sure you tell users what the issue is, without going too technical. For example, let’s assume, your app’s servers overloaded and crashed due to traffic surge. If that’s the scenario, don’t get too technical and spam them with crash logs and error codes. That’s for your developers, not users! An appropriate error message could say “Our servers are currently busy”.

    The Google Chrome browser balances information and detail very well. It even adds a bit of humor to it. It has a brilliant empty state that not only tells us what’s wrong. But also suggests how to fix the problem.

    Android Chrome App — Offline State

    Here’s what Chrome achieves with this design.

    1. A generic error message that everyone can understand
    2. Suggests steps to resolve the error
    3. An error code — for the tech savvy?
    4. Download Page Later button— automatically download page for viewing when the internet is back on
    5. T-Rex game— it’s actually a game you can play to kill time until your internet comes back

    FUN FACT: Why Google Chrome shows a dinosaur when offline?

    Here’s another example.

    Desk Empty States by YiJing Z — Dribbble

    Remember that not every scenario is the same. This would have already become evident to you. For example, for a retry page load, it makes sense to have a retry button. But what about an email app with an empty Spam screen?

    Now that’s clear, we can see how to actually design it.


    How to Design Empty States

    To make blank slate useful, consider inserting quick tutorials, videos, help tips, call to action-elements, screenshot of the page when it is in “normal” stage – anything that helps the user and makes him happy with your app. — Patternry

    Here is a couple of tips on how to design effective Empty States. Let’s go through them one at a time.

    1. Be informative

    When an empty state occurs, it is visible to the user. Tell them why they’re seeing this screen.

    When a user sees an empty state, 2 things should be conveyed.

    1. Purpose of the screen (what can I expect to see here?)
    2. Why am I currently seeing an empty state?

    Dropbox favorites Image credit: tympanus.net

    Copy in design is very powerful. It effectively communicates what users need to know. The lesser the words used, the better.

    If you read carefully, the copy answers both those questions above. It tells us:

    1. What is this screen?
    2. What’s the use of marking a file as a ‘favorite’?

    2. Handle Failure States— Don’t scare your users

    If it’s an error, tell them what went wrong. Take it a step further by suggesting how to resolve the error. Remember the Google Chrome example?

    Here’s what you can do with Empty States for an error:

    • show a non-technical copy for error text
    • suggest possible steps to resolve the error (as simple and short as possible)
    • Don’t use technical jargon that can confuse users
    • Allow them to reload (retry loading a page)

    Image credit: emptystat.es

    3. Encourage Users to take action

    A simple, yet highly-effective way to get users to interact, is to use a CTA (Call-to-Action).

    A call-to-action (usually abbreviated as CTA) is an image or line of text that prompts your visitors, leads, and customers to take action. It is, quite literally, a “call” to take an “action.”— blog.hubspot.com

    In other words, for our apps, CTAs are buttons. Big bold, attention hogging buttons. When a user sees a screen, the should immediately be able to see that CTA (button). That’s what makes it effective.

    Material Design provides us a Floating Action Button. That’s a perfect candidate for a CTA!

    Some examples would be a note-taking app. Prompt first-time users to add a new note by using a CTA button. Or a recipe app, where the CTA is to add a new recipe.

    Marvel App – Project empty state by Murat Mutlu — Dribbble

    Yet for some screens, there is simply nothing to do. Example, Gmail Spam screen.

    Gmail App — Spam

    4. Display Starter Content

    Remember the Google Keep app? We spoke about it as an example for Empty States. That’s called Starter Content.

    Evernote app — starter content for first-time users

    With this, 2 goals can be achieved.

    1. Help familiarize users with how notes work
    2. Use these ‘starter content’ notes to to flaunt the app’s features

    Consider Twitter, where every new user needs to follow few people first to get started. In this way, no first-time user’s home feed is going to be empty. This can also be seen as a way of Twitter reinforcing what it’s all about.

    5. Stick to your brand— be consistent

    You might have a lot of freedom when designing Empty States. But make sure you stick to your brand.

    By that I mean, make sure you stick to your styleguide and color palette. The last thing you want is a screen that feels alien within your entire app.

    Alright, this might not be a design tip that’s specific to Empty States. But even so, it is still important. It’s easy to get carried away!

    For example, if your brand color is blue. For the sake of emphasis, don’t make your Empty State’s CTA button red! Agreed that you might want to emphasize an alert or danger. But don’t do it at the cost of inconsistency.

    Course Dashboard by Shashank — MaterialUp

    6. Use Humor

    Sometimes, humor can play a big role in damping down the seriousness of an issue.

    A great example of using humor in design is Mailchimp. They know how well to design it so that it engages the user.

    Mailchimp — what users see after sending a campaign. Image credit: smashingmagazine.com

    So before you use humor, make sure you it’s in the right context. For example, a good place to use it would be content not found screens (empty search results).

    On the contrary, a bad place to use it would be in an error state. Say a failed task. It’s worse if the error was on your part.

    Using humour is fun and is a welcome relief. But also think of scenarios when a customer comes to your site to complain, or they have a problem with your product or service. They may not be in the best mood and that humorous message could be a tipping point for a customer to leave permanently. — spotless.co.uk

    Empty state concepts infused with personality by Tasnadi Otto — MaterialUp

    7. Keep it simple

    Arriving at the last design tip, this is the most important one to remember.

    With all the tips mentioned above, it’s easy to include everything and go overboard! Don’t do that.

    Remember that simple designs are always more effective.

    Here’s a great empty state interaction. It’s lovely, but it’s also so fancy that if my app is simple and not animation-heavy. I wouldn’t attempt anything like this, just for an Empty State!

    Empty State by Jordan Nelson — MaterialUp

    An Empty State is supposed to be a lightweight screen. If there is an action to be performed, make sure it’s just one. Don’t offer many points of interaction on a single empty state! That’s just confusing.


    Takeaway

    To summarize everything, Empty States are an excellent opportunity to engage with users. It might seem insignificant in the larger picture. But even the smallest of things matter.

    Attention to detail matters because when you show that you care about the small details, people trust you to care about the big ones. — Meg Robichaud (Shopify UX)

    User retention with apps are already very hard. So use every chance you have to keep them. Because once they leave, it’s difficult to get them back.

    Remember that no screen should be a dead-end for your users.

    Wrap up

    Keeping these simple design tips in mind will help you create effective Empty States:

    1. Be informative — tell users why they’re seeing this screen
    2. Handle failure — tell why the error occurred and suggest a fix
    3. Use a CTA — encourage users to take action
    4. Consider Starter Content — great way to familiarize users with your app
    5. Be consistent — stick to your brand’s design guidelines
    6. Use Humour — reduce the seriousness of an issue. Use carefully
    7. Keep it simple — nothing over the top. Remember simple = effective.

    I hope this article will help you design better, effective Empty States. Use them to your advantage for better user retention!

    Lastly, if you need some design inspiration, these resources have you covered.

    Resources for your inspiration —

    Thanks for reading!

  • Customize Color with Styled Google Maps in Android

    Customize Color with Styled Google Maps in Android

    You can now style and customize your Google Maps colors and more. In this Android tutorial, let’s see how we can do that in our apps.

    Google Maps has added this ability across all platforms. This means regardless of whether you use Google Maps for Web, iOS or Android, you’ll be able to style them.

    By default, Google Maps looks like this.

    Default Google Maps

    We’re all used to this and by no means am I saying it looks bad. But say I want to display a map that corresponds to my brand color scheme.

     

    Directions Module by David Rodriguez

    Now imagine if my only option was to display the default Google maps, with it’s default colors. It wouldn’t go well with the design, would it? The color scheme of the map won’t be in harmony with the rest of the design. In other words, it sticks out, like a sore thumb.

    In such scenarios, we need a map that reflects our brand theme. Our brand color palette. This wasn’t possible before.

    But now, Google allows Styled maps. Using this, we can customize the map to look the way we want. This includes modifying colors, with a very high degree of control.


    Getting Started

    We’ll start by creating a new Android Studio project. Thankfully, we have pre-defined templates (for Activities) to start with. Activity templates were introduced in Android Studio 1.4.

    So when you create a new project, chose the ‘Google Maps Activity’ template.

    Android Studio – Activity Templates

    Here are the project settings:

    • minSdkVersion – 14
    • targetSdkVersion – 26

    Thanks to this, we don’t have to spend a lot of time configuring the Maps SDK and whatnot. I remember the first time I tried using Maps in Android (back in 2012). It took me well over an hour to simply display a Map!

    But you don’t have to worry anymore as we’ve come a long way from that!

    Configuring Google Maps

    Once the project has loaded, Android Studio will open the google_maps_api.xml file by default.

    Auto-generated maps_api.xml

    You’ll notice there is one step to follow to get your Google Maps API Key. Trust me, this is nothing compared to the amount of steps earlier!

    So follow the comments on the file. Don’t worry, I’ll still walk you through them. but you’ll have to grab the URL and keys from the google_maps_api.xml file’s comments.

    1. Go to the URL provided – console.developers.google.com

    You’ll land on a page like this.

    Create a new project in Google Developer Console

    Select ‘Create a Project’ from the dropdown and then hit the Continue button.

    2. Create Google Maps API Key

    In the next step (screen), click the ‘Create API Key’ button.

    Creating new API key…

    3. Get your generated API Key

    Google now generated your Maps API key. So copy it and paste it in your XML file for the string name ‘google_maps_key’. Replace the ‘YOUR_KEY_HERE’ with your actual API key!

    You can optionally set up API Key restrictions if you want (see screenshot above). It’s fairly simple. Click restrictions and you’ll get a screen like this.

    Generated API key restrictions

    Choose ‘Key restriction’ as ‘Android Apps’ and hit Save button. Note that you don’t have to bother about the Package name and SHA-1 certificate fingerprint. You’ll realize that the fingerprint is same as the one in your Android Studio project comments.

    In other words, Google took care of that for you too. Sweet? Now let’s move on.

    With our API key in place, we’re finally ready to use Google Maps.

    But before we get to styling, let’s check if Maps itself works. So run your app and check it out.

    It’s always better to test every step of the way. Otherwise, you’ll never know what went wrong where.

    NOTE:
    Google Maps needs Google Play Services to work. So it’s safe to always run the app on a real device. Or, you can configure and use an AVD that includes Google APIs with Play Services.

    Here’s how Google Maps loads on my phone.

    Default Google Maps – Android

    It works just fine. So let’s finally move on to styling it.

    Using Styled Maps

    Google Maps can load styling options via two different formats:

    1 – JSON file

    You load the JSON file in the onMapReady() method.

    @Override 
    public void onMapReady(GoogleMap googleMap) 
    {
        try { 
            // Customise map styling via JSON file 
            boolean success = googleMap.setMapStyle( MapStyleOptions.loadRawResourceStyle( this, R.raw.style_map_json));
    
            if (!success) {
                Log.e(TAG, "Style parsing failed.");
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Can't find style. Error: ", e);
        }
    
    1. String resource Using a string resource works in a similar way.
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
        try { 
            // Customise map styling via String resource 
            boolean success = googleMap.setMapStyle(new MapStyleOptions(getResources() .getString(R.string.style_json)));
    
            if (!success) {
                Log.e(TAG, "Style parsing failed.");
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Can't find style. Error: ", e);
        }
    

    Now we know how to load our Map styles. But how do we actually create our style? Let’s look at that next.


    Creating a Color Theme for Google Maps

    I’ll put it bluntly. There are two ways you can go about it.

    One, write a JSON file. Manually writing every property (do you even know them?).

    Or two, using the Map Styling Wizard.

    In other words, save yourself time and frustration. Go with the second option. Use the Styling Wizard. It’s a no-brainer. Seriously!

    Google Maps Styling Wizard

    Welcome to Google Maps Styling Wizard

    For this part, you just play around with the Styling Wizard. Adjust the density of features depending on how much detail you want on the map. Then select a basic, pre-defined theme to work with. Finally, you can click on ‘MORE OPTIONS’ to alter the properties of each Map object. Trust me, there’s a LOT of things you can customize that it’s easy to get lost.

    Abundant customization options in Map Styling Wizard

    I’ve chosen very light, pastel-like colors for the map. These are colors mainly for the terrain, parks, water and highways.

    Once you’re done, click the FINISH button. Next, copy the JSON from the popup that appears.

    Auto-generated JSON from Styling Wizard

    Head over to your Android Studio project and create a new file under Project/app/src/main/res/raw/maps.style.json.

    This JSON file is where we’ll paste the JSON copied from the Maps Style Wizard. Now all that’s left is to tell Google Maps to load its style from this JSON file.

    Remember we spoke about how to do this in the onMapReady() method?

    Let me remind you again. Now that we have our JSON file ready, we can call it in like this.

    Open MapsActivity.java and go to the onMapReady() method. The template has this method already implemented for you.

    So with the default template existing, here’s how to load the Styled Map.

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
        mMap = googleMap;
        try {
            boolean success = mMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.maps_style));
    
            if (!success) {
                Log.e(TAG, "Style parsing failed.");
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Can't find style. Error: ", e);
        }
        ...
    }
    

    It’s actually just one line of code. The try catch block just makes it look verbose.

    With Styled Maps now loaded, run your app and check it.


    Styled Maps – Output

    Based on the colors I chose against a Grey- themed Google Map, mine looks like this.

    My custom styled Google Maps

    I changed parks to purple color. Just so I visually know that Styled maps are working. I know it’s an ugly map. But I’m sure you can do better!

    Wrap Up

    In this Android tutorial, we saw how to Style our default-looking Google Maps.

    First, we created an Android Studio project, using the Maps Activity template. We then created an API key to use with Maps.

    Next, we used the Maps Styling Wizard to configure Google Maps to our liking. Then, we pasted the generated JSON over to our project. Finally, we told Google Maps to load its styling from that JSON file.

    Where to from here?

    That’s all there is to it! With Styled maps, it is now possible to customize Google Maps to be more relevant to your app color-scheme. No more out-of-place looking Maps. If used properly they can now blend well with your UI designs.

    How are you going to customize your map? I’m very interested to see what you’ll come up with. Show me in the comments below.

    Header Image Credits: Asar Morris

  • Android O Tutorial: Supporting Picture-in-Picture (PIP)

    Android O Tutorial: Supporting Picture-in-Picture (PIP)

    Picture in Picture or PIP is a feature famously seen on YouTube and Android TV apps. It minimizes your content (typically video), keeping it pinned to a corner while you carry out your other tasks.

    In other words, the video keeps playing in the corner, while you continue using the app.

    What’s Picture-in-Picture?

    Picture-in-picture mode lets apps run a video activity in the pinned window while another activity continues in the background. – developer.android.com

    Let me rephrase that for you. Open YouTube and watch a video. You’ll notice you can minimize that video and continue to watch it whilst using the app.

    PIP in YouTube app

    Recently, even Facebook added it. You can minimize a video and continue watching it, while you’re scrolling through your newsfeed. Sweet!

    PIP in Facebook


    Until now, to implement such a feature, Android Developers like you and I had two options:

    1. Write our own – won’t come off pretty
    2. DraggablePanel – works fine

    Yep, I heard you. DraggablePanel was our only choice. While that was and is a fine library, I’d say there’s a better option today.

    Picture in Picture with Android O

    When Android Nougat came, we saw PIP support for Android TV. It was only a matter of time when it came to mobile. Finally, in the next version, Android O added support for mobile too!

    In this article, I’ll tell you how to enable support for mobile. Developers who have worked on Android TV with Nougat should feel right at home. But don’t worry if you haven’t. You’ll be able to follow along just as easy.

    Getting Started – Project Setup

    To use all of Android O’s features properly, you need Android Studio 3.0 Preview. This works as a standalone install compared to your existing, stable Android Studio.

    If you already have all of that setup, then feel free to go ahead with this tutorial.

    If you haven’t setup Android Studio 3.0 Preview, I strongly recommend you go through the Android O: Getting Started article first. It covers how to setup Android Studio Preview to use API 26.

    Anyways, for your reference, here’s what we’ll be using:

    • Android Studio 3.0 Preview
    • Gradle version – 3.0.0-alpha4
    • compileSdkVersion – 26
    • buildToolsVersion – 26.0.0
    • Support Library Version – 26.0.0-beta2

    You can use these to update your Gradle build accordingly.

    Lastly, make sure you’re using Google’s maven repository. Open your project-level build.gradle file.

    buildscript {
       repositories {
          google()
          jcenter()
       }
       dependencies {
          classpath 'com.android.tools.build:gradle:3.0.0-alpha4'
       }
    }
    
    allprojects {
       repositories {
          google()
          jcenter()
       }
    }
    // ...

    Adding PIP Support on Android

    First, we need to create an Activity and declare that it supports picture-in-picture. So go ahead and create a new Activity. I call mine PipActivity.java.

    Next, open your AndroidManifest.xml. Here, we’ll declare that PipActivity supports Picture-in-Picture. We do so by using the supportsPictureInPicture attribute.

    <activity
                android:name=".PipActivity"
                android:launchMode="singleTask"
                android:supportsPictureInPicture="true"
                android:theme="@style/AppTheme.NoActionBar" />

    NOTE:
    Developers who have worked with Android Nougat for TV might notice that the resizeableActivity attribute is no longer required for PIP. However, keep in mind that if you set resizeableActivity to false, then the supportsPictureInPicture attribute is ignored.

    Handling Activity Duplication and Recreation

    Notice the launchMode attribute in the Manifest. Any guesses why it’s required?

    Avoiding Activity Duplication – Using Launch Modes

    The Launch Mode singleTask tells Android that there should be only one instance of that Activity.

    In other words, if I keep starting PipActivity, only one instance of it should open. There should never be any duplicates.

    This scenario is highly likely and is mandatory that you handle it.

    For example, take the YouTube app. You’re browsing through a playlist and you open a particular video. Then, if you enter PIP mode, you’re back to the playlist screen. Now, if you click the same video again, we want the existing video to enlarge back up. Or, if you click another video, we want PIP to maximize with the clicked video playing. We do not want another (PIP) screen to open.

    The singleTask Launch Mode handles this for us.

    Preventing Activity Recreation

    If you’re that daring person who wants to support PIP and orientation changes, then you’ll need one extra attribute.

    Add the configChanges attribute to your Manifest to prevent PipActivity from being recreated each time on orientation change.

    This will be extremely handy when your PiP includes a player (which will most likely be the scenario).


    Starting Picture-in-Picture mode

    Now that we’ve prepared our Activity, the next step is to trigger PIP mode.

    So to do that, we need to create a simple layout first. Open your Activity’s XML layout.

    XML Layout

    Honestly, I leave this to your imagination. But for the sake of this tutorial, I’m going to pretend we have a UI that includes a player.

    PIP XML layout

    The layout is very simple. Here’s the XML code for the same.

    <FrameLayout
        android:id="@+id/frame_mock_player"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:background="@color/colorAccent">
    
        <ImageButton
            android:id="@+id/btn_minimize"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top|start"
            android:layout_margin="@dimen/layout_margin"
            android:background="?selectableItemBackgroundBorderless"
            android:src="@drawable/ic_picture_in_picture_alt_black_24dp"
            android:tint="@android:color/white" />
    
        <!--Other Player UI here-->
    </FrameLayout>
    
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#EFEFEF">
    
        <!--Video details UI here-->
    
    </FrameLayout>
    

    In short, we have a FrameLayout that would be our player. We also have a button that indicates switching to Picture in Picture mode.

    You can add that icon via a right click on res/drawable folder> New> Vector Asset. In this way, you can choose from the entire set of Google’s Material Design icons.

    TIP:
    These icons that you import are by default, black in color. So make sure to tint vector icons for pre-Lollipop devices.

    Triggering PIP

    With the layout complete, it’s now time to start Picture-in-Picture. So to do that, head over to PipActivity.

    PiP is triggered when we click the button on the top-right. So we’ll write our entire logic inside that button’s click listener.

    mBtnPip.setOnClickListener(view -> { 
       if (android.os.Build.VERSION.SDK_INT >= 26) { 
          //Trigger PiP mode 
          try { 
             Rational rational = new Rational(mFramePlayer.getWidth(), 
                                             mFramePlayer.getHeight());
    
                    PictureInPictureParams mParams =
                            new PictureInPictureParams.Builder()
                                    .setAspectRatio(rational)
                                    .build();
    
                    enterPictureInPictureMode(mParams);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(PipActivity.this, "API 26 needed to perform PiP", Toast.LENGTH_SHORT).show();
            }
        });

    There are a couple of things going on here, so let’s tackle it one at a time.

    If you’ve seen the PIP animation, notice that the ‘ratio’ the player maintains when maximized and minimized, are the same.

    So it’s essential that we do the same. You can simply enter Picture-in-Picture mode using enterPictureInPictureMode(). But you can pass in some optional parameters if you wish. That’s what we’re doing here.

    We will maintain the ratio of our dummy player to be the same in PIP mode. For that, we need to pass a PictureInPictureParams object.

    NOTE:
    I’m triggering PIP mode only for API 26 and above. Ideally, as a fallback, you must hide or disable this feature. For the sake of this tutorial, I’m displaying a Toast message.


    Best Practices

    Now that we’ve seen how to launch PIP, there are a couple of things to keep in mind.

    Adapting UI to PIP mode

    When in PIP mode, avoid displaying any UI controls except the video player.

    When PipActivity enters PIP mode, we need to hide everything displayed except the video. So to do that, we need some way to know that we’re currently in PIP.

    We can detect when an Activity enters Picture-in-Picture using the onPictureInPictureModeChanged() method.

    In our case, the only UI control we need to hide is the PIP ImageButton on the top-left.

    @Override
        public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
            super.onPictureInPictureModeChanged(isInPictureInPictureMode);
            if (!isInPictureInPictureMode) {
                mBtnPip.setVisibility(View.VISIBLE);
            } else {
                mBtnPip.setVisibility(View.GONE);
            }
        }

    TIP:
    You can override onPictureInPictureModeChanged() either in your Activity or Fragment.

    Updating PIP Content

    Remember we discussed the importance of singleTask Launch Mode to avoid duplicate PIPs? I even used the YouTube app as an example.

    If you think carefully about that example, there’s one thing that we don’t know how to handle. When we’re in PIP, and we click on another content, we solved the duplication problem. But PIP must be updated with the content that we clicked. How can we do that?

    Use the onNewIntent() method to update your PIP with the new content data.

    Managing Playback

    Once our Activity goes into PIP mode, we need to ensure that the content playback continues.

    NOTE:
    When you switch to PIP mode, Android considers that Activity to be in a paused state. Hence it calls that Activity’s onPause() method.

    Forget PIP for a second. If your Activity goes into onPause(), then ideally, you’ll pause your playback too. But if you’re in PIP mode, make sure you don’t pause playback.

    Android’s given us a handy method isInPictureInPictureMode() that we can use to handle this.

    @Override 
    protected void onPause() { 
        super.onPause();
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
                && isInPictureInPictureMode()) {
            // Continue playback...
        }
        // Not in PIP & Activity is paused. Pause playback if required....
    }

    Output

    Finally, we’ve done everything that’s needed to make Picture in Picture work. We’ve also made sure to handle its common scenarios. Let’s see how it works.

    Make sure you create an Android Emulator (AVD) that runs API 26 (Google Play System Image). Once you’ve done that, run your app. You should get a working PIP like this.

    Wrap up

    Picture-in-Picture was finally brought to Android Smartphones thanks to Android O. In this article, we briefly saw how to prepare Android Studio to use the latest Android O SDK (API 26). Then we learnt how to use PIP.

    Although PIP is generally used for video playing content, this tutorial excluded a guide for video playing. This was done to ensure the focus stays on Picture in Picture.

    SOURCE CODE:
    Sample working Project available on GitHub.

    Where to from here?

    Remember, there is no hard and fast rule that PIP must only be used for video playing content. Its usage is only restricted to your imagination.

    How will you use PIP in your app? Have any questions? Let me know in the comments below.

    Lastly, if you liked reading this, don’t forget to share (on the left). If you want updates on the next article, subscribe below.