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 - myPath2canvas.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.LayoutContainerclass 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.

KTX 和 Kotlin android extension 都到底是个啥?相关推荐

  1. Android KTX 和 Kotlin android extension对比

    参考: KTX 和 Kotlin android extension 都到底是个啥? Android KTX KTX 是被称为Android之光的 JakeWharton 写的 Android KTX ...

  2. Android KTX与Kotlin Android Extensions

    Android KTX Android KTX是Google官方推荐的一套便利的Android API扩展函数库.因还处于beta阶段,相关API并不丰富,但既然是出自JakeWharton大神之手, ...

  3. kotlin android 4,Kotlin Android Extensions: 与 findViewById 说再见 (KAD 04)

    时间:Aug 16, 2017 原文链接:https://antonioleiva.com/kotlin-android-extensions/ 在 Kotlin1.1.4版本 发布后,原作者依据 K ...

  4. 【翻译】ANDROID KTX – 使用Kotlin进行Android开发

    原文地址:ANDROID KTX – ANDROID DEVELOPMENT WITH KOTLIN [正在翻译中] 介绍 Android KTX is an open source library ...

  5. Android 开发都有哪些好书值得一读?

    code小生 一个专注大前端领域的技术平台公众号回复Android加入安卓技术群 Android 近几年不单单更新的快,新引进的技术也增加了不少,总体是 Google 在向一个更好的趋势发展,在谋划更 ...

  6. kotlin学习笔记——Kotlin Android Extensions

    Kotlin Android Extensions是另外一个团队开发的,它是一个插件所以不需要依赖别的库.当前仅仅包含view的绑定,会自动创建很多属性让我们直接访问xml中的view,我们就不需要明 ...

  7. 【译】迁移被废弃的Kotlin Android Extensions插件

    原文:Migrating the deprecated Kotlin Android Extensions compiler plugin 作者:Ahmad El-Melegy 在Kotlin 1.4 ...

  8. [译] 开发者(也就是我)与Rx Observable 类的对话 [ Android RxJava2 ] ( 这到底是什么?) 第五部分...

    本文讲的是[译] 开发者(也就是我)与Rx Observable 类的对话 [ Android RxJava2 ] ( 这到底是什么?) 第五部分, 原文地址:Dialogue between Rx ...

  9. android 抽屉,凌乱了 Android的抽屉到底要不要?

    原标题:凌乱了 Android的抽屉到底要不要? 由于iPhone的APP图标直接布满桌面而没有抽屉概念,所以小编打一开始就不喜欢它(好吧,实际是买不起).早期Android区别于iOS最大的特征就是 ...

最新文章

  1. 厉害了!这支获得国家级荣誉的智能车队
  2. Python教程:快速掌握列表的常用方法
  3. .NET Windows服务应用程序
  4. 8 包含min函数的栈
  5. 父盒子高度为子盒子总高度自动撑满 height: fit-content; //设置内容高度
  6. 关于NSIS脚本的Demo
  7. war压缩命令_BetterZip mac版(超强解压缩软件)
  8. vue如何取消下拉框按回车自动下拉_如何用大白菜重装系统|大白菜怎么重装系统教程详解...
  9. 数字化转型方法论_50+企业数字化转型、管理的方法论,这本书到底有什么干货?...
  10. 斐波那契序列 Fibonacci
  11. 微信小程序制作家庭记账本之一
  12. 2018 ideal 链接数据_利用 IDEA HTTP 请求文件访问 API 接口
  13. Hbase的过滤器分类
  14. python中if嵌套语句_选择结构-if..elif语句和if语句的嵌套
  15. 更有效的编写QQ空间、CSDN、博客园图文并茂的文章
  16. 计算机学业水平测试初中生操作题,初中学业水平考试信息技术考试操作题常见题型及作答方法...
  17. uni-app 对照设计稿还原不同屏幕像素适配(iPhone X)
  18. 1000kv电子加速后的速度
  19. 路由器DNS 劫持攻击情况
  20. 老板彻底晕菜!美女是这样要求加工资

热门文章

  1. 兰大转专业计算机考试内容,兰州大学教务处
  2. 虚拟机ping不通网关之大坑
  3. 1200.火柴棒等式
  4. 51单片机学习:LED点阵实验(显示图像)
  5. 用铸造涂料中的消泡剂消除泡沫能对生产能起到哪些作用?
  6. [转载]国画技法视频教学网址指南
  7. 泸西 阿庐古洞 那些你不知道的好去处
  8. Java1.8新特性之Stream的使用
  9. 港联证券|十字星是见顶信号吗?十字星是见顶信号还是出货信号?
  10. SLO如何实现快速,可靠的应用程序交付