Kotlin學習筆記——Android擴展插件之視圖綁定

前言

在Android中使用Kotlin語言開發,必須在build.gradle中引入Android Kotlin插件(apply plugin: 'kotlin-android')。但是在Android開發中,Kotlin還提供了一些擴展插件,擴展插件有什麼作用呢?下面給大家演示一下。

在佈局文件中編寫控件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/tvMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

要獲取佈局中TextView這個控件,在Activity中,傳統的做法是使用findViewById()

val tvMsg = findViewById<TextView>(R.id.tvMsg)
tvMsg.text = "This is a TextView"
tvMsg.setOnClickListener {
    Toast.makeText(this, tvMsg.text.toString().trim(), Toast.LENGTH_LONG).show()
}

但是,如果你使用了Kotlin的Android擴展插件,無需使用findViewById()獲取控件,可以直接通過佈局文件中的id進行訪問

import kotlinx.android.synthetic.main.activity_main.* // 引入佈局文件

// tvMsg是對Activity的一項擴展屬性,與activity_main.xml中聲明的id爲tvMsg的控件具有一樣的類型,所以是TextView
tvMsg.text = "This is a TextView"
tvMsg.setOnClickListener {
    Toast.makeText(this, tvMsg.text.toString().trim(), Toast.LENGTH_LONG).show()
}

以上的示例,是Kotlin的Android擴展插件中的視圖綁定,看着是不是很方便簡潔呢?其實Kotlin的Android擴展還有很多其他用途。

使用Kotlin Android擴展

配置擴展

Kotlin Android擴展,必須是在Gradle環境下才能使用

配置擴展,僅需要在模塊的 build.gradle 文件中啓用 Gradle 安卓擴展插件即可:

apply plugin: 'kotlin-android-extensions'

導入合成屬性

在需要用一行代碼便可導入指定佈局文件中的所有屬性

import kotlinx.android.synthetic.<channel_name>.<layout_xml_file_name>.*

以上可變參數中:
channel_name是指渠道名稱,如果你的項目支持多個渠道(productFlavors),這裏寫對應的渠道名稱,如果沒有,默認爲main
layout_xml_file_name是佈局文件名稱

導入完成後即可調用在xml文件中以視圖控件命名屬性的對應擴展,如下:

<TextView
    android:id="@+id/tvMsg"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

你將獲得一個名爲tvMsg的屬性

tvMsg.text = "This is a TextView"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章