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:
[sourcecode language=”java”]MapView mapView = (MapView) findViewById(R.id.mapView);[/sourcecode]
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:
[sourcecode language=”java”]
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);
}
[/sourcecode]
Using Kotlin Extensions
You enable the Kotlin Android Extensions Gradle plugin in your app projects build.gradle file:
[sourcecode language=”java”]
apply plugin: ‘com.android.application’
apply plugin: ‘kotlin-android’
// add this for Kotlin Android Extensions
apply plugin: ‘kotlin-android-extensions’
[/sourcecode]
You can import all widget properties for a specific layout in the file activity_main.xml with the following:
[sourcecode language=”java”]import kotlinx.android.synthetic.main.activity_main.*[/sourcecode]
You can now invoke your MapView with the id name ..
[sourcecode language=”java”]
<!– 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>
[/sourcecode]
.. without initializing with findViewById:
[sourcecode language=”java”]mapView.map(ArcGISMap)[/sourcecode]
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!
Article Discussion: