How to add a Kotlin class in an Android Studio pro

2019-08-21 07:21发布

问题:

I have been working with Android Studio for a while. Recently I have heard about kotlin programming language and I wanted to try to include a class in kotlin language to my project.

There is the problem that whenevr I want to create a new Activity for example, the .java class is auto-generated. Also I see no way to cretae a .kt (kotlin) file manually.

So does anyone know how to setup a .kt file in Android Studio, so that I am able to fill it with code in kotlin language?

回答1:

First, install Kotlin plugin in Android Studio. Restart Android Studio.
Now create a new project with no activity.
Then navigate to src>main>java><your_package_name>.
Right Click on <your_package_name>, select New>Kotlin Activity and go ahead with configuration.
Now naviagte to src>main>java><your_package_name>/<activity_name>.kt and open it.
After opening it, you will see Kotlin not configured message.
Just click configure action and run your project. That's it!



回答2:

One way to do it is by converting Java file to Kotlin file. Open the java class, and from menu bar choose Code -> Convert Java File to Kotlin File.



回答3:

Get Android Studio 3 preview and when you start a new project click the option to add Kotlin support... Once in your project you'll see options to create Kotlin class when you right click