Using Kotlin Android Extensions with ArcGIS Android

Google just recently announced official support for Kotlin in Android so we can now take advantage of techniques to enhance the development experience with ArcGIS Android.  One way we can do this is through the use of Kotlin Android Extensions.

Accessing View Resources

In Android Java, once you provide resources in your app, e.g. a MapView, you can apply it by referencing its resource ID which are defined in your projects R class that is automatically generated.  You can access resources in code by passing a resource ID as a method parameter.  For example, you can access a MapView using findViewById:

MapView mapView = (MapView) findViewById(R.id.mapView);

While there are libraries available to simplify accessing resources, using Kotlin and the  Android Extension plugin simplifies resource access and is not dependent on runtime or annotations allowing full Kotlin code to display an ArcGIS Map in a MapView with the following:

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val mMap = ArcGISMap(Basemap.Type.TOPOGRAPHIC, 34.056295, -117.195800, 16)
    mapView.map(map);
}

Using Kotlin Extensions

You enable the Kotlin Android Extensions Gradle plugin in your app projects build.gradle file:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
// add this for Kotlin Android Extensions
apply plugin: 'kotlin-android-extensions'

You can import all widget properties for a specific layout in the file activity_main.xml with the following:

import kotlinx.android.synthetic.main.activity_main.*

You can now invoke your MapView with the id name ..

<!-- MapView -->
<com.esri.arcgisruntime.mapping.view.MapView
    android:id="@+id/mapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
</com.esri.arcgisruntime.mapping.view.MapView>

.. without initializing with findViewById:

mapView.map(ArcGISMap)

You can see Kotlin in action with ArcGIS Android in our MobileMapPackage demo on GitHub.  We will be looking to make more Kotlin code available through the Android SDK so get up to speed with Kotlin here as once you start using Kotlin it will be hard to return back to Java for developing Android apps!

This entry was posted in App Developers, Developer, Mobile and tagged , , , . Bookmark the permalink.

Leave a Reply