Kotlin的android扩展:对findViewById说再见(KAD 04)

2023-05-20,,

作者:Antonio Leiva

时间:Dec 12, 2016

原文链接:http://antonioleiva.com/kotlin-android-extensions/

你也许已厌倦日复一日使用findViewById编写Android视图。或是你可能放弃它转而使用著名的Butterknife库。那么你将会喜爱Kotlin的Android扩展

Kotlin的Android扩展

Kotlin的Android扩展是Kotlin插件的正规插件之一,它无缝覆盖Activities的视图,Fragments y视图。

让我们看看它是怎样简单。

在我们代码中集成Kotlin的Android扩展

虽然你要使用一插件时可以将其集成到代码中,但是你还是需要在Android模块中填加额外的apply:

 apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

这些都是你需要添加的。这样你就准备好使用它。

在Activity或Fragment中覆盖视图

此时,在你的Activity或Fragment中覆盖视图与直接在XML中用视图id定义一样方便。

想象你有这样的XML:

 <?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"> <TextView
android:id="@+id/welcomeMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!"/> </FrameLayout>

如你所见,TestView有welcomeMessage id。

只需在你的MainActivity这样编写:

 override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main) welcomeMessage.text = "Hello Kotlin!"
}

为了能够使用它,你需要专门import(这句我写在下面),而且IDE能够自动添加引入(import)它。这不是很容易吗!

import kotlinx.android.synthetic.main.activity_main.*

插件生成代码能够存储视图缓存(cache),这样你再次访问视图时,就不需要另一个findViewById。

由一个视图覆盖其它视图

我们有这样的视图:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"> <ImageView
android:id="@+id/itemImage"
android:layout_width="match_parent"
android:layout_height="200dp"/> <TextView
android:id="@+id/itemTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"/> </LinearLayout>

如你在其内添加adapter。

你只需用这个插件,就可直接访问子视图:

 val itemView = ...
itemView.itemImage.setImageResource(R.mipmap.ic_launcher)
itemView.itemTitle.text = "My Text"

尽管插件也帮助你填写了import,不过这类有一点点不同:

import kotlinx.android.synthetic.main.view_item.view.*

对此有一些事情你需要知道:

    在编译时,你可以从任何其他视图引用任何视图。这意味着你可以从一视图引用任何视图,而非一定是其的子视图。但是,在运行时这将失败,这是因为其试图覆盖的视图不存在。
    在这种情况下,视图没有为Activities和Fragments缓存起来。

但是,你只要仔细利用它,它还是非常有用的工具。

结论

你已经知道怎样在Kotlin中方便的处理Android视图。用一个简单的插件,我们就可以在扩展后忽略所有那些涉及视图恢复的糟糕代码。这插件将按照我们的要求特性产生没有任何问题的正确的类型。

Kotlin的android扩展:对findViewById说再见(KAD 04)的相关教程结束。

《Kotlin的android扩展:对findViewById说再见(KAD 04).doc》

下载本文的Word格式文档,以方便收藏与打印。