您的位置:首页 > 移动开发 > Android开发

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

2016-12-15 22:48 686 查看
作者: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:

1 apply plugin: 'com.android.application'
2 apply plugin: 'kotlin-android'
3 apply plugin: 'kotlin-android-extensions'


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

在Activity或Fragment中覆盖视图

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

想象你有这样的XML:

1 <?xml version="1.0" encoding="utf-8"?>
2 <FrameLayout
3     xmlns:android="http://schemas.android.com/apk/res/android"
4     android:layout_width="match_parent"
5     android:layout_height="match_parent">
6
7     <TextView
8         android:id="@+id/welcomeMessage"
9         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:layout_gravity="center"
12         android:text="Hello World!"/>
13
14 </FrameLayout>


如你所见,TestView有welcomeMessage id。

只需在你的MainActivity这样编写:

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


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

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


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

由一个视图覆盖其它视图

我们有这样的视图:

1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2               android:orientation="vertical"
3               android:layout_width="match_parent"
4               android:layout_height="match_parent">
5
6     <ImageView
7         android:id="@+id/itemImage"
8         android:layout_width="match_parent"
9         android:layout_height="200dp"/>
10
11     <TextView
12         android:id="@+id/itemTitle"
13         android:layout_width="match_parent"
14         android:layout_height="wrap_content"/>
15
16 </LinearLayout>


如你在其内添加adapter。

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

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


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

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


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

在编译时,你可以从任何其他视图引用任何视图。这意味着你可以从一视图引用任何视图,而非一定是其的子视图。但是,在运行时这将失败,这是因为其试图覆盖的视图不存在。

在这种情况下,视图没有为Activities和Fragments缓存起来。

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

结论

你已经知道怎样在Kotlin中方便的处理Android视图。用一个简单的插件,我们就可以在扩展后忽略所有那些涉及视图恢复的糟糕代码。这插件将按照我们的要求特性产生没有任何问题的正确的类型。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: