Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Kotlin 開發 Android(四):自訂 View 與 Android Extensions

編輯:關於 Android 開發

原文標題:Kotlin for Android (IV): Custom Views and Android Extensions
原文連結:https://antonioleiva.com/kotlin-android-custom-views/
作者:Antonio Leiva(https://antonioleiva.com/about/)
發布日期:2015-05-07

讀完 Kotlin 的擴充函式與預設參數之後,你可能會好奇接下來還有什麼。如第一篇所說,這門語言的目標之一,就是讓 Android 開發變得更輕鬆,所以值得聊的東西還很多。

自訂 View

先前談 Kotlin 的限制時提過:早期版本(M10 之前)無法建立自訂 View。原因是我們只有一個建構子,雖然可以靠可選參數變出各種組合,通常也夠用:

class MyClass(param: Int, optParam1: String = "", optParam2: Int = 1) {
    init {
        // Initialization code
    }
}

就靠這唯一的建構子,我們可以有四種建立方式:

val myClass1 = MyClass(1)
val myClass2 = MyClass(1, "hello")
val myClass3 = MyClass(param = 1, optParam2 = 4)
val myClass4 = MyClass(1, "hello", 4)

但當我們想繼承 View 來自訂 Android 元件時就有問題了:自訂 View 需要多載多個建構子(Context、Context+AttributeSet、Context+AttributeSet+defStyleAttr),而當時的 Kotlin 做不到。所幸從 M11 開始,我們能用類似 Java 的寫法宣告多個 secondary constructor。以下是一個保持正方形比例的 ImageView:

class SquareImageView : ImageView {

    public constructor(context: Context) : super(context) {
    }

    public constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
    }

    public constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = getMeasuredWidth()
        setMeasuredDimension(width, width)
    }
}

寫法不複雜,雖然略顯冗長,但至少路是通的。

Kotlin Android Extensions

M11 還帶來一個新外掛,讓我們能用更簡潔的方式存取 XML 中宣告的 View。用過 ButterKnife 的人應該會覺得似曾相識,只是它更省事。

Kotlin Android Extensions 本質上就是 View Binding:讓你能直接用 XML 中的 id 存取 View,不需要任何額外註解,也不需要 findViewById。

啟用方式是在主 build.gradle 的 buildscript 依賴中加入 classpath:

buildscript {
    ...
    dependencies {
        ...
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

假設有這樣一個 main.xml:

<FrameLayout
    xmlns:android="..."
    android:id="@+id/frameLayout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/welcomeText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</FrameLayout>

要在 Activity 中使用,只要匯入該 XML 的 synthetic 屬性:

import kotlinx.android.synthetic.<xml_name>.*

在我們的例子中就是:

import kotlinx.android.synthetic.main.*

接著就能直接用 id 當屬性使用:

override fun onCreate(savedInstanceState: Bundle?) {
    super<BaseActivity>.onCreate(savedInstanceState)
    setContentView(R.id.main)
    frameLayout.setVisibility(View.VISIBLE)
    welcomeText.setText("I'm a welcome text!!")
}

總結

這兩項特性清楚顯示 Kotlin 團隊非常在意 Android 開發者的日常體驗。他們還推出了 Anko,用 DSL 直接從 Kotlin 檔案建立版面,我在 GitHub 上的專案裡有一些範例可以參考。

下一篇會談 Lambda 表達式,以及它如何幫助我們精簡程式碼、擴展語言能力。以我的看法,相較於 Java 1.7,這是 Kotlin 最強的一塊。

前一篇:https://www.cnblogs.com/figozhg/p/4996136.html

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved