美文网首页
Kotlin for Android 探索

Kotlin for Android 探索

作者: DON_1007 | 来源:发表于2017-05-22 16:31 被阅读0次

    Kotlin for Android 官方教程 ,官方文档是最好的入门教程。作为一个传统的使用Java语言开发Android程序的开发者来说,最关注的还是Kotlin与Java语言的兼容性,如果能想苹果的SwiftObject C一样能相互调用就更好了。下面看一下官方文档是怎么告诉我们的?

    • Compatibility: Kotlin is fully compatible with JDK 6,完全兼容JDK 6,Kotlin程序能在旧的Android设备上运行。
    • Performance: A Kotlin application runs as fast as an equivalent Java one,简单说就是程序跟Java开发的跑的一样快,下面还说使用lambda表达式写的代码跑的更快
    • Interoperability: Kotlin is 100% interoperable with Java, allowing to use all existing Android libraries in a Kotlin application.百分之百兼容Java语言,可以直接使用现有的所有的Android 代码库
    • Footprint: Kotlin has a very compact runtime library, which can be further reduced through the use of ProGuard. the Kotlin runtime adds only a few hundred methods and less than 100K to the size of the .apk file.Kotlin 有一个非常精简的运行时库,编译出来的apk文件体积更小
    • Compilation Time: Kotlin supports efficient incremental compilation,incremental builds are usually as fast or faster than with JavaKotlin编译速度跟Java相比一样或者更快
    • Learning Curve: For a Java developer, getting started with Kotlin is very easy. The automated Java to Kotlin converter included in the Kotlin plugin helps with the first steps.如果你是一个Java开发者,Kotlin对于你来说就很好学,并且有插件可以自动将Java代码转成Kotlin代码

    关于Kotlin的开发工具,还是使用Android Studio,3.0版本以上的Android Studio集成的有Kotlin插件,如果是3.0以下的就需要自己安装Kotlin插件。具体方法是Android Studio->File->Settings->Plugins搜索Kotlin

    Paste_Image.png
    选中Kotlin进行安装,插件安装之后重启Android Studio
    重启之后新建一个Demo程序,建好之后的打开MainActivity,选择Help->Find Action输入 Convert Paste_Image.png
    点击选中,就可以把原先的Java代码转换成Kotlin代码
    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
        }
    }
    
    

    现在程序可以运行,但是会崩溃。这是因为Gradle文件中还没有配置Kotlin插件。先随便在MainActivity中写几句代码,稍等一会IDE就会提示你Kotlin还没有配置。

    Paste_Image.png

    选中需要配置的module

    Paste_Image.png

    选中之后打开 app 的gradle文件,点击 Sync Now,等同步完成之后,重新运行程序

    device-2017-05-22-115256.png

    相关文章

      网友评论

          本文标题:Kotlin for Android 探索

          本文链接:https://www.haomeiwen.com/subject/saxyxxtx.html