KTX 和 Kotlin android extension 都到底是个啥?

本文深入探讨了KTX库如何简化Kotlin在Android开发中的使用,以及Kotlin Android Extensions插件如何提升开发效率,包括View Binding、LayoutContainer支持、Flavor支持等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. KTX是什么

 

Android官网对于KTX的介绍:https://developer.android.com/kotlin/ktx

KTX 是被称为Android之光的 JakeWharton 写的,GitHub地址:https://github.com/android/android-ktx/

A set of Kotlin extensions for Android app development. The goal of Android KTX is to make Android development with Kotlin more concise, pleasant, and idiomatic by leveraging the features of the language such as extension functions/properties, lambdas, named parameters, and parameter defaults. It is an explicit goal of this project to not add any new features to the existing Android APIs.

Google翻译如下:

一套用于Android应用开发的Kotlin扩展。 Android KTX的目标是通过利用语言的功能(如扩展函数/属性,lambdas,命名参数和参数默认值),使Kotlin的Android开发更简洁,愉快和惯用。 此项目的明确目标是不向现有Android API添加任何新功能。

到这里,KTX的原理也清楚了,就是利用了Kotlin的一些语法特性。

但是目前这个项目很久没有更新了,而且处于 1.0.0-alpha1,期待1.0稳定版的到来。

同时,JakeWharton 也在呼吁大家加入到这个项目中来,一起贡献代码,

 

要详细了解 Android KTX,请观看我们的 DevBytes 视频

 

 

官网举例如下:


Kotlin:

val uri = Uri.parse(myUriString)

Kotlin with Android KTX:

val uri = myUriString.toUri()

Kotlin:

sharedPreferences.edit()
    .putBoolean("key", value)
    .apply()

Kotlin with Android KTX:

sharedPreferences.edit {
    putBoolean("key", value)
}

Kotlin:

val pathDifference = Path(myPath1).apply {
    op(myPath2, Path.Op.DIFFERENCE)
}

canvas.apply {
  val checkpoint = save()
  translate(0F, 100F)
  drawPath(pathDifference, myPaint)
  restoreToCount(checkpoint)
}

Kotlin with Android KTX:

val pathDifference = myPath1 - myPath2

canvas.withTranslation(y = 100F) {
    drawPath(pathDifference, myPaint)
}

Kotlin:

view.viewTreeObserver.addOnPreDrawListener(
    object : ViewTreeObserver.OnPreDrawListener {
        override fun onPreDraw(): Boolean {
            viewTreeObserver.removeOnPreDrawListener(this)
            actionToBeTriggered()
            return true
        }
    })

Kotlin with Android KTX:

view.doOnPreDraw {
     actionToBeTriggered()
}

 

所有的API文档地址:https://android.github.io/android-ktx/core-ktx/

API如下,都以AndroidX开头,独立更新,更新速度大于Android的SDK,以后可能会直接加入到Android Support Library中

androidx.animation

 

androidx.content

 

androidx.content.res

 

androidx.database

 

androidx.database.sqlite

 

androidx.graphics

 

androidx.graphics.drawable

 

androidx.net

 

androidx.os

 

androidx.text

 

androidx.time

 

androidx.transition

 

androidx.util

 

androidx.view

 

2. Kotlin Android Extensions是什么

Kotlin Android Extensions 是Kotlin官方推出的一个插件,提高android开发体验的一个东西

官网文档介绍地址:https://kotlinlang.org/docs/tutorials/android-plugin.html

主要有以下功能:

1. View Binding

每个Android开发人员都熟悉findViewById()函数。 毫无疑问,它是潜在错误和令人讨厌的代码的来源,难以阅读和支持。 虽然有几个库可以提供此问题的解决方案,但这些库需要为每个公开的View注释字段。

Kotlin Android Extensions插件允许我们获得与其中一些库相同的体验,而无需添加任何额外的代码。

实质上,这允许以下代码:

// Using R.layout.activity_main from the 'main' source set
import kotlinx.android.synthetic.main.activity_main.*

class MyActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // Instead of findViewById<TextView>(R.id.textView)
        textView.setText("Hello, world!")
    }
}

这里textview作为Activity的一个扩展属性,它和在activity_main.xml中声明的具有相同类型(即TextView类型)。

对其原理感兴趣的,可以反编译这个成Java文件,然后查看其实现原理,其实其内部有一个SparseArray来维护所有的view。

 

⚠️注意:其实Kotlin Android Extensions是Kotlin插件的一部分,所以其实要使用Kotlin Android Extensions,不需要安装额外的插件,要做的只是启用它(当然前提是,你已经使用了kotlin的gradle插件),即在module的build.gradle中加入:

apply plugin: 'kotlin-android-extensions'

2. LayoutContainer Support

LayoutContainer和下面的 Parcelable目前都处于实验阶段,不建议在生产项目中使用,如果要启用,可在build.gradle添加如下:

androidExtensions {
    experimental = true
}

Android Extensions 插件支持不同种类的container,常见的如Activity,Fragment,View,但是可以将任何实现了LayoutContainer接口的类转换成container,如下代码中在ViewHolder中使用:

import kotlinx.android.extensions.LayoutContainer

class ViewHolder(override val containerView: View) : ViewHolder(containerView), LayoutContainer {
    fun setup(title: String) {
        itemTitle.text = "Hello World!"
    }
}

3. Flavor support

具体参考:https://kotlinlang.org/docs/tutorials/android-plugin.html#flavor-support

4. View Caching

调用findViewById()会导致缓慢,尤其是在View的层级很大时,所以Android Extensions 插件视图使用container来最小化地调用findViewById(),在下例中,findViewById()只被调用了一次:

class MyActivity : Activity()

fun MyActivity.a() { 
    textView.text = "Hidden view"
    textView.visibility = View.INVISIBLE
}

但是在下面这种情况,就不会再使用缓存的View:

fun Activity.b() { 
    textView.text = "Hidden view"
    textView.visibility = View.INVISIBLE
}

5. 更改View的缓存策略

可以对container中View的缓存策略进行全局的,或者仅当前类去修改,可选择的缓存方式有:HASH_MAP,SPARSE_ARRAY,NONE。以前默认是HASH_MAP,现在默认好像改成了SPARSE_ARRAY

具体参见:https://kotlinlang.org/docs/tutorials/android-plugin.html#changing-view-caching-strategy

6. Parcelable序列化

该功能也处于试验性阶段,参见:https://kotlinlang.org/docs/tutorials/android-plugin.html#parcelable

使用方式如下:

import kotlinx.android.parcel.Parcelize

@Parcelize
class User(val firstName: String, val lastName: String, val age: Int): Parcelable

使用要求,所有序列化的参数要写在主构造函数中,

也可以自定义序列化逻辑

支持的序列化类型:

upported Types

@Parcelize supports a wide range of types:

  • Primitive types (and its boxed versions);
  • Objects and enums;
  • StringCharSequence;
  • Exception;
  • SizeSizeFBundleIBinderIInterfaceFileDescriptor;
  • SparseArraySparseIntArraySparseLongArraySparseBooleanArray;
  • All Serializable (yes, Date is supported too) and Parcelable implementations;
  • Collections of all supported types: List (mapped to ArrayList), Set (mapped to LinkedHashSet), Map (mapped to LinkedHashMap);
    • Also a number of concrete implementations: ArrayListLinkedListSortedSetNavigableSetHashSetLinkedHashSetTreeSetSortedMapNavigableMapHashMapLinkedHashMapTreeMapConcurrentHashMap;
  • Arrays of all supported types;
  • Nullable versions of all supported types.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值