Eric Maxwell - Big Nerd Ranch Tue, 19 Oct 2021 17:47:11 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 Kotlin Multiplatform in 2020 https://bignerdranch.com/blog/kotlin-multiplatform-in-2020/ Tue, 17 Dec 2019 16:05:57 +0000 https://nerdranchighq.wpengine.com/?p=4024 Kotlin Multiplatform is quickly becoming a solid contender in the multiplatform solution space. This article explains what makes the platform stand out against the competition and what to expect for Kotlin Multiplatform in 2020 and beyond.

The post Kotlin Multiplatform in 2020 appeared first on Big Nerd Ranch.

]]>
This month over 1700 engineers, entrepreneurs, and business leaders from around the world flew to Copenhagen, Denmark to attend KotlinConf, a two day conference run by JetBrains, the company behind the Kotlin programming language and Intellij. Attendees came to learn more about the language that has been adopted now by over 2.2 million users and powers 60% of the top 1000 apps in the Google Play Store.

Some notable themes emerged this year including several upcoming performance improvements, language stabilizations, and feature improvements to coroutines, Kotlin’s approach to concurrency. The star of the show however was clearly Kotlin Multiplatform, with 7 sessions dedicated to the subject including 2 sessions from engineers at Square and Careem, sharing their own experiences with it.

Kotlin Multiplatform is moving from an early stage, engineering focused, experiment into a solid contender in the multiplatform solution space.

What is Kotlin Multiplatform?

Kotin Multiplatform is a mechanism for sharing code across multiple platforms. This means you can share common data, state, and business logic across Windows, Linux, MacOS, Web, iOS and Android, as well as any Java Virtual Machine (JVM) based platform not covered by the aforementioned operating systems.

This is not a new concept. In the mobile application space today there are other popular solutions to sharing code between mobile platforms, such as Flutter and React Native, and many others that have come before them; Cordova, PhoneGap, Kony, Titanium, to name a few. Even outside of mobile, this has been attempted before. If you consider the idea of languages like C# compiling to intermediate language for the Common Language Runtime (CLR) and Java compiling to bytecode for the Java Virtual Machine (JVM), these languages and their platforms were designed with portability and sharing in mind.

Kotlin Multiplatform has the same goal as its predecessors but accomplishes it in a different way. Whereas Java, C#, React Native and many others compile or target an intermediary language that requires a bridging adapter or virtual machine layer to interpret at runtime, Kotlin Multiplatform code compiles to the same native output as the rest of the code running on the platform. In this way, it transcends platforms that were previously not reachable for a single language. To put it in practical terms, Java needs a JVM, C# needs a CLR, React Native needs a JavaScript bridge to interpret the logic and invoke the appropriate native UI framework code, Kotlin Multiplatform does not. It compiles down to JVM bytecode, JavaScript, or native machine code as needed, based on the platform target.

The Case for Kotlin Multiplatform

The pitch for Kotlin Multiplatform is put simply by Kotlin’s lead design engineer, Andrew Breslav, “Code Sharing, Skill Sharing, plus 100% access to the native platforms”. The idea is that sharing code across all of the platforms your application(s) support, using a common programming language, leads to fewer bugs, shortens development times, and carries lower maintenance costs since your team is maintaining a smaller code base.

Having a common language also means that developer skillsets are heavily transferable between teams.

Answers to Commonly Expressed Concerns

Many of the concerns common to multiplatform solutions, such as the fear of adopting (and then supporting) a new language, experiencing degraded runtime performance, or losing the native look-and-feel of your applications, fall by the wayside.

Team Support

Kotlin is already used by over 53% of professional Android developers today and that growth is accelerating. It’s being used in server-side development too at large tech companies like Intuit, Expedia, and Pivotal.

Kotlin is also easy to learn, with a language syntax that is remarkably similar to other popular languages like Swift, Scala, Groovy, and Java. You may find that your team already has the right skill sets.

Performance

Since Kotlin Multiplatform code compiles to the exact same format as the target platform, it is just as performant as its native counterparts. Your users (and engineers) won’t be able to tell the difference.

Native UI/UX

Kotlin Multiplatform encourages sharing only where it makes sense. As an example, you may wish to share your core business logic and state, but allow each platform to decide exactly how to consume and present that data. This gives your customers a fully native experience while reaping the benefits of code sharing.

Considerations & Risks

The biggest risk to Kotlin Multiplatform is timing and consequently the sparseness of third-party library support. Some basic libraries like HTTP client libraries and data serialization libraries exist and there is a promise for more to come in 2020, with the release of Kotlin 1.4, including a DateTime library. But, for the moment it’s likely that you will need to implement some things yourself.

In addition, Kotlin multiplatform is designed to share code, but not be a drop in replacement for all of the APIs of each platform you target. So, it should be noted that you will need at least some knowledge of each platform you support. This is different than a multiplatform solution like Flutter where Flutter comes with its own UI componentry and is very much a drop in replacement for the native UI stack.

The Future

In 2020, expect Kotlin Multiplatform adoption to accelerate. While it has not quite reached 1.0 stable, major tech companies are already starting to use it.

At Big Nerd Ranch, we see a lot of potential in it and are excited to see where it goes!

The post Kotlin Multiplatform in 2020 appeared first on Big Nerd Ranch.

]]>
Adding Tools Attributes to your Toolbox https://bignerdranch.com/blog/adding-tools-attributes-to-your-toolbox/ https://bignerdranch.com/blog/adding-tools-attributes-to-your-toolbox/#respond Mon, 01 Apr 2019 10:00:00 +0000 https://nerdranchighq.wpengine.com/blog/adding-tools-attributes-to-your-toolbox/ Android Tools Attributes are a critical element of any well designed app that uses DataBinding, RecyclerViews or top level navigation, such as a Navigation Drawer or Bottom Navigation View. This post teaches the importance of using them and how you can apply them to your project provide design-time hints to Android Studio about what type of data and attributes will be applied to your views at runtime, so that it can render them at design time.

The post Adding Tools Attributes to your Toolbox appeared first on Big Nerd Ranch.

]]>

Android Tools Attributes are a critical element of any well designed app that uses Data Binding, a RecyclerView or top level navigation, such as a Navigation Drawer or Bottom Navigation View. Yet, they are often overlooked by developers.

In this post, we’ll look at why these attributes are important and how you can apply them to provide design-time hints to Android Studio about what type of data and attributes will be applied to your views at runtime.

To illustrate the concepts, we will look at a sample app called Weather. This app displays a list of cities and their current weather forecast summary. Clicking on one of the summary rows, shows a details screen with more information about “today’s” forecast.

Running Weather Application

The app looks relatively straightforward when you see it running, but how does that look in the Layout Editor at design time. Well that depends!

This project is built using Data Binding and uses a RecyclerView to show the list of cities on the summary screen. If you’re not using tools attributes to give design time hints, it will look something like this…

Illustration of Design Preview with No Tools Attrs Applied

As you can see, there is no indication of what this view may look like when rendered on a device. It’s hard to even tell what the screens are, let alone:

  • How will this look on a 5” screen vs a 7” screen?

  • How does it look in landscape vs portrait?

  • How does screen density affect the layout?

This becomes even more obvious when you are using the Navigation Architecture Component, where instead of a rich graph showing each of your screens and their relationships to each other:

Navigation Graph Google Sample w/ Tools Attrs ProvidedImage generated from navigation_graph of the Google Codelabs – Navigation Sample

…you see a bunch of white boxes with no meaning, connected by arrows.

Navigation Graph Google Sample w/out Tools AttrsImage generated from navigation_graph of the Google Codelabs – Navigation Sample(With tools layout references removed.)

Coming back to the weather app sample. This is a fairly simple app consisting of two screens. So why can’t Android Studio just figure this crap out? 😡

Weather Nav Graph

The answer is that Android Studio does not have enough information to figure it out. Data-bound views use binding expressions to describe how to evaluate the contents of the view at runtime. Similarly, RecyclerViews depend on dynamic views being attached at runtime, facilitated by a RecyclerView.Adapter.

At design time, Android Studio has no way of knowing what data will be placed in the views. However, you as the developer do know what types of data will be placed into your views. The tools attributes give you a way to provide hints to Android Studio so that it can render an accurate preview of your views at design time.

Note: Of course things like (the effects of density, orientation, and screen size) are things that you will want to test before shipping your app, but you could get a good idea of how it will render at design time if you use Tools Namespace attributes in your layouts.

Tools Namespace

The Tools Namespace is an XML namespace that declares attributes you can apply to your views. These attributes give design time rendering hints (such as which item layout to show in a RecyclerView) and designate compile time behaviors (such as specific lint rules to ignore or even specific resources to keep during proguard minification). You are probably already using some of these attributes and may not have noticed.

If you’ve ever suppressed a warning in your layout using the Android Studio quick assist helper, you may notice that it adds a tools:ignore attribute to the element that was triggering the lint error or warning.

Suppressing a lint warning with Android Studio quick assist adds a `tools:ignore` attr

There are 3 categories of attributes:

We will focus on the design-time view attributes in this post.

Now, there are dozens of tools attributes ranging from ones that define sample text to show in a text view or a sample image source for an <ImageView>, all the way to illustrating DrawerLayout states and providing sample data for your RecyclerView. You can find a complete list in the Android Documentation. One good thing to remember though is that any android attribute associated with the view has a corresponding tools attribute.

Common Scenarios

A few common examples where tools attributes can help.

Providing Sample Text

Consider adding a tools:text attribute for any android:text attribute that has a binding expression value.

<TextView
    ...
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@{vm.forecast}"  
    tools:text="Expect a high today of 96, with winds out of the northwest at 21 mph" />

Providing a Sample Image Source

Add a tools:src inside <ImageViews>s where the image is dynamically loaded.

<ImageView
    android:id="@+id/weather_icon"
    android:contentDescription="@{vm.weatherIconContentDesc}"
    tools:src="@mipmap/ic_snowy"
    app:weatherIcon='@{vm.weatherIcon}'   /> 
    <!-- This example uses a BindingExpression to provide `app:weatherIcon` not shown here -->

Designating a RecyclerView’s Item Layout

Use tools:listItem to indicate what layout will be inflated and placed into your RecyclerView at runtime.
(This assumes homogeneous item types).

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/weather_list_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutManager="LinearLayoutManager"
    tools:listitem="@layout/weather_item" />

If you really want to be fancy, you can populate lists with sample data, as Thibault de Lambilly shows in his post titled, Android Tools attributes: listItem & sample data rocks!. Although I personally find that providing sample data usually requires more effort to setup and maintain than is worth the effort. Still, if you have a RecyclerView that has vastly different data or you would like to see specific data entries and how they render at design time, you have this as an option.

Improving Weather App

Applying these techniques to Weather App (for the list, details and weather summary item layouts) its navigation graph looks much easier to follow, as can be seen in the diagram below.

CompletedWeatherExample
Weather navigation graph with Tools Attrs applied

You can find the sample project for this post in my Github Repo. If you have questions, the best way to reach out to me is on Twitter @emmax.

Thanks for reading!

The post Adding Tools Attributes to your Toolbox appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/adding-tools-attributes-to-your-toolbox/feed/ 0
Navigation Architecture Components https://bignerdranch.com/blog/navigation-architecture-components/ https://bignerdranch.com/blog/navigation-architecture-components/#respond Wed, 30 May 2018 10:00:23 +0000 https://nerdranchighq.wpengine.com/blog/navigation-architecture-components/ The Navigation component is comprised of a set of tools, APIs and resources, that allow you to build your app navigation declaratively and visually. It makes certain tasks which used to be fairly tedious, like animating screen transitions and creating deep links into your application, now very easy.

The post Navigation Architecture Components appeared first on Big Nerd Ranch.

]]>

Announcing Jetpack & the Navigation Architecture Component

This year’s Google I/O conference was packed with a lot of exciting announcements for Android Developers, who have long been asking for a Google recommended approach to building apps for the Android platorm and the tooling to support it. Google started an initiative to do this last year by launching Architecture Components, a collection of components to simplify Android development, while guiding developers down the path of what Google considers to be best practices. In other words, exactly what the community had been asking for. These included Room, the very popular object-relational mapping tool for SQLite, LiveData a generic, observable container for data, and a few others.

This year they expanded and rebranded the architecture components into a larger umbrella of tools, components, and architectural guidelines, called Jetpack. For me, one of the more exciting additions that Google added to Jetpack this year was a new architecture component called, Navigation.

The Navigation component is comprised of a set of tools, APIs and resources, that allow you to build your app navigation declaratively and visually. It makes certain tasks which used to be fairly tedious, like animating screen transitions and creating deep links into your application, now very easy. In addition, Navigation makes it easy for developers to follow one of Google’s newly announced architectural guidelines, which is that Android applications should be built using a single Activity whenever possible, utilizing Fragments for individual screens within the app.

Overview

So what does this component look like and how does it work?

If you’re using Navigation, you’ll define the layout of your app in terms of a series Destinations and Actions. Destinations represent individual screens or places that the user can go within your application, and Actions represent named routes between those Destinations.

All of these Destinations and Actions are defined in a new resource file type, called a navigation resource. A navigation resource is just an XML file that lives in your apps res directory, alongside the other cast of characters like layout, menu, drawable, etc.

Here’s a very simple example showing what a navigation resource file might look like for a two-screen application.

Navigation Resource Example

Storing this information in XML makes makes it easy to diff navigation changes over time, but it could become tedious and error prone to manage this by hand as your application grows. So the Android Studio team has built a very simple, yet powerful view to go along with the navigation resource, called the Navigation Editor.

Navigation Resource shown in Resource Editor

The Navigation Editor provides a visual of each screen, or Destination, that is wired up within this navigation resource. As you can see in the screenshot above, the editor is even able to pull in the design time rendering of each individual Destination. This makes it super easy to keep track of which screen is which and their relationships to each other.

The arrow that you see connecting crimes_fragment to add_new_crime_fragment in this example represents the Action defined in the navigation XML above. This visual is cool, but what is really amazing to me is how easy it is to build these Actions directly through the editor by simply dragging from the right edge of one Destination to the left edge of another.

Invoking the Actions

The navigation resource defines which Destinations and Actions are available, but it doesn’t define how the actions are invoked. Invoking an action still requires some code in most cases, but once again, Google has given us some really nice tooling to simplify the process.

Traditionally you might have done something like the following in your activity to display a new screen based on the click of a button:

// If launching into a new activity
addCrimeButton.setOnClickListener {
    startActivity(Intent(this, NewCrimeActivity::class.java))
}
-- or --

// If just replacing a fragment in the current activity 
addCrimeButton.setOnClickListener {
    supportFragmentManager.beginTransaction()
        .replace(R.id.detail_fragment_container, NewCrimeFragment())
        .commit()
}

With Navigation, you’ll do something more like this, for both cases…

addCrimeButton.setOnClickListener(
   Navigation.createNavigateOnClickListener(
           R.id.action_crimes_fragment_to_add_new_crime_fragment)
)

Though as noted earlier. Google’s new recommendation is that each screen would be represented as a Fragment.

Notice that with Navigation approach, the same navigation code works regardless of whether the destination is a Fragment or an Activity. Furthermore, notice the one key thing missing from the Navigation version… There is no fragment transaction!! 🎩 Well… to be fair, it’s actually still happening. It’s just completely abstracted away by the framework now 🦄

This is just a quick glance at Navigation and how it works, but I haven’t even touched on some of the reasons I’m super excited about it…

Amazing Features

These are the top 3 reasons I’m excited about Navigation, in order of awesomeness. 🤓

Automatic Fragment Transaction Management

You no longer have to write the boilerplate code to manage Fragment Transactions yourself.

Automatic Back and Up Navigation Management

Navigation, uses the Destinations and Actions that you define in your navigation to build and manage the Android back stack for you on your behalf. It can supply up and back navigation within your application automatically and with appropriate behavior based on where the user is within your app and how they got there.

Built in Deep Linking

What used to be a tedious, error prone process of deep linking into your application and providing proper up and back navigation, is now an almost trivial process.

You simply declare a deep link on a Destination in the Navigation Editor and the framework handles the creation of any necessary intent filters in your AndroidManifest.xml, and synthetically builds the proper back stack for you. This is something you are certain to hear more excitement about from the community as developers start using Navigation and something I can’t wait to start exploring further.

Deep Linking using Navigation Editor

Getting Started

Now is the perfect time to jump in and get started with the Navigation Architecture Component as it is currently still in early Alpha. And, while this means that there might be a few kinks along the way, it also means that the APIs aren’t 100% locked down yet. This means that there is still time to provide feedback and help shape the final API. In fact, Lukas Bergstrom, the Product Manager for Architecture components, explicitly said during the Navigation Component talk presented at IO 2018, that Google has released Navigation as an alpha for that exact reason. He also added that once the API is stable, Navigation will be part of the “default experience” when you create an Android app. The IDE will start you in the Navigation Editor.

You can get started today by downloading the latest canary build of Android Studio. I’d encourage you to also check out the Navigation Architecture Talk from Google IO 2018. It’s filled with really good information about the motivations and future directions they see for this exciting new component.

Finally, there have already been some great tutorials posted by GDE’s and other enthusiastic developers in the community. I found this detailed tutorial by Joe Birch to be very helpful in my research for this post.

I hope you’ll check it out!

Cheers 🎉

The post Navigation Architecture Components appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/navigation-architecture-components/feed/ 0