Using Kotlin to develop Android app first experience

Source: Internet
Author: User

Using Kotlin to develop Android app first experience

Last night, the latest Google IO conference formally Kotlin determined for the official development of language, as an Android development bird, how can not taste fresh in time?

A brief introduction to Kotlin

Before development, many students must have a lot of questions, Kotlin in the end there is what good, how and existing projects coexist? Are there any Kotlin features in Java? Well, let's see it all.

The following is excerpted from: Kotlin's official website: https://www.kotlincn.net/docs/reference/android-overview.html

Kotlin is ideal for developing Android apps, bringing all the benefits of modern language into the Android platform without introducing any new restrictions:

    • Compatibility: Kotlin is fully compatible with JDK 6, ensuring that Kotlin applications can run on older Android devices without any problems. The Kotlin tool is fully supported in Android Studio and is compatible with the Android build system.
    • Performance: Because of the very similar bytecode structure, Kotlin applications run at a speed similar to Java. With Kotlin support for inline functions, code that uses lambda expressions usually runs faster than code written in Java.
    • Interoperability: Kotlin can interoperate with Java 100%, allowing all existing Android libraries to be used in Kotlin applications. This includes annotation processing, so data binding and Dagger are the same.
    • Occupancy: Kotlin has a very compact runtime library that can be further reduced by using Proguard. In the actual application, the Kotlin runtime only adds hundreds of methods and the. apk file is less than 100K in size.
    • Compile time: Kotlin supports efficient incremental compilation, so there is additional overhead for clean-up builds, which are often as fast or faster as Java.
    • Learning curve: For Java developers, Kotlin is easy to get started with. The automatic Java-to-Kotlin converter included in the Kotlin plugin helps take the first step. Kotlin Heart Print provides a guide to the main functions of the language through a series of interactive exercises.
Kotlin Case Study for Android

Kotlin has been successfully adopted by a number of major companies, some of which share their experience:

    • Pinterest has successfully introduced Kotlin into their applications, with 150 million people per month.
    • Basecamp's Android app is 100% Kotlin code, they report huge differences in programmer happiness, as well as a huge improvement in quality and speed of work.
    • Keepsafe's app Lock application has also been converted to 100% Kotlin, reducing the number of source code lines by 30% and reducing the number of methods by 10%.
      Tools for Android Development
The Kotlin team provides a set of tools beyond standard language capabilities for Android development:
    • Kotlin Android extension is a compiler extension that allows you to get rid of the code in the Findviewbyid () call and replace it with the synthesized compiler generated properties.
    • Anko is a library that provides a Kotlin-friendly wrapper around the Android API, and a DSL that can replace the layout. xml file with Kotlin code.
Next
    • The Android and Kotlin Introductory Tutorial guides you through installing the Kotlin plugin into Android Studio and creating your first Kotlin application.
    • For more in-depth introduction, please check the site's reference documents and Kotlin heart print.
    • Another good resource is Kotlin for Android developers, which guides you through the process of creating a real Android application in Kotlin.

Finally, attach "Kotlin for Android Developers", a guide for learning to use Kotlin to develop Android apps.

Developing Android Apps with Kotlin

Before we begin to learn how to use Kotlin to develop Android apps, we first need to be prepared for the environment in which Android Studio 3.0 must be configured first.

Create a Kotlin development project

The project creation here is not different from the normal Android app project, except that the Include Kotlin support option is checked when the project is created.

The default created activity is already Kotlin code that looks very similar to the Java code itself:

The Kotlin file ends with . KT .

The default creation of the Kotlin file is also placed in the same location as the Java file, if you need to make the Kotlin file with the Java file, then you can add the following configuration in the corresponding Gradle file:

android {   sourceSets {       ‘src/main/kotlin‘   }}

In this case, all Kotlin files created by default will be placed in the /kotlin/ directory.

Add Kotlin to existing projects

If you need to add Kotlin support to an existing project, you only need to select Kotlin in the source language option when the activity is newly created:

Converting Java code to Kotlin code

Tools for translating Java code into Kotlin code are available in Android Studio 3.0. You only need to open the corresponding Java file, and then choose Code------to Kotlin file on the menu bar to complete the conversion.

However, it is important to note that the tool can do most of the syntax conversion, individual types, such as arrays may have some problems in the conversion, you need to manually adjust. Bloggers I found this problem while practicing, but it was quickly corrected by a grammar document. It is found that Kotlin is much better than Java in terms of simple syntax. For example, the following section of code:

        val bitmaps = LargePicLoadHelper.cutItemImage(cutImage, itemImageHeight)        cutImage.recycle()        in bitmaps) {            val imageView = ImageView(this)            imageView.setImageBitmap(i)            linearLayout.addView(imageView)        }        textView.postDelayed({            in bitmaps) {                i.recycle()            }        1000)

This code is much more concise when polling an array than the Java foreach Loop, where I represents a bitmap object, and bitmaps is an array. Isn't it simple?

Using Java code with Kotlin

Kotlin provides a very powerful interoperability , what is this interoperability? That is, Kotlin can be very convenient to call Java code, Java code can also be very convenient to call the Kotlin code. To what extent is this convenient? Kotlin can call Java code directly . If you know about JNI, you know how simple and convenient it is to kotlin interoperability.

Use Kotlin to declare activity:

class MyActivity : AppCompatActivity() {  override fun onCreate(savedInstanceState: Bundle?) {    super.onCreate(savedInstanceState)    setContentView(R.layout.activity)  }}

To set a click event using Kotlin:

val textView = findViewById(R.id.text) as TextViewtextView.setOnClickListener {    Toast.makeText(this,"Hello Kotlin!",Toast.LENGTH_SHORT).show()}

See no, the above Setcontentview and the following toast is the Android-provided API that we can use directly. And the new Onclicklistener object is not required inside the Setonclicklistener Method! Direct write click to achieve it! And the first parameter of the toast. This is in Java must write Activity.this, and here only write this can be ! Isn't it niubility?

Finally, I hope you can join the following Kotlin development Learning Exchange Group, together explore learning kotlin!

Using Kotlin to develop Android app first experience

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.