Kotlin Android 扩展(二)

版权声明:文章转载请标明出处,谢谢! https://blog.csdn.net/huang3513/article/details/75020062

前言

作为一个android程序猿,最让人苦恼的就是繁琐的代码,比如:findViewById(),相信每个人对这个方法都在熟悉不过了,潜在的Bug和脏乱的代码令后续的开发很难着手。随着android studio的普及,插件的使用不断地发展,后来使用ButterKnife插件,使我们对findViewById()摒弃了好多繁琐的工作。显然这个插件带来了解决方案,然而对于运行时依赖库,需要为每个View注解变量字段。

Kotlin优势

Kotlin能够提供与开源库相同体验,但我们不需要添加任何额外的代码,使代码更简洁,也不影响任何运行时的体验。

因此,我们可以写出如下代码:

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        /**
         * Kotlin编码:实现textview数据显示
         */
        textview.setText("Kotlin-2017-07-12");

        /**
         * Kotlin编码:实现OnClickListener监听事件
         */
        button.setOnClickListener {
            System.out.println("info button is running")
        }
    }
}

textview是activity_main布局中的一个id,是对AppCompatActivity的一项扩展属性,与在activity_main.xml中声明具有同样的类型。

使用Kotlin扩展

依赖配置
安卓扩展是Kotlin IDEA插件的组成之一,因此不需要安装单独的插件。

我们只需要在build.gradle文件中启用Gradle安卓扩展插件即可:

apply plugin: 'kotlin-android-extensions'

导入合成属性

仅需要一行即可非常方便导入指定布局文件中所有控件属性:

扫描二维码关注公众号,回复: 3060236 查看本文章
import kotlinx.android.synthetic.main.<布局>.*

假设当前布局文件是 activity_main.xml,我们只需要引入
kotlinx.android.synthetic.main.activity_main.*。

若需要调用 View 的合成属性(在适配器类中非常有用),同时还应该导入
kotlinx.android.synthetic.main.activity_main.view.*。

导入完成后即可调用在xml文件中以视图控件命名属性的对应扩展, 比如下例:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.lw.hxfkotlindemo.MainActivity">

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:text="Kotlin"
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="45dp" />

</LinearLayout>

将有一个名为 textview的属性:

activity.textview.setText("Kotlin-2017-07-12")

学习记录而已,不喜勿喷!

猜你喜欢

转载自blog.csdn.net/huang3513/article/details/75020062