Kotlin学习笔记——Android扩展插件之视图绑定
前言在Android中使用Kotlin语言开发,必须在build.gradle中引入Android Kotlin插件(apply plugin: 'kotlin-android')。但是在Android开发中,Kotlin还提供了一些扩展插件,扩展插件有什么作用呢?下面给大家演示一下。在布局文件中编写控件<?xml version="1.0" encoding="utf-8"?>...
前言
在Android中使用Kotlin语言开发,必须在build.gradle中引入Android Kotlin插件(apply plugin: 'kotlin-android')。但是在Android开发中,Kotlin还提供了一些扩展插件,扩展插件有什么作用呢?下面给大家演示一下。
在布局文件中编写控件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="@layout/activity_main">
<TextView
android:id="@+id/tvMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
要获取布局中TextView这个控件,在Activity中,传统的做法是使用findViewById()
val tvMsg = findViewById<TextView>(R.id.tvMsg)
tvMsg.text = "This is a TextView"
tvMsg.setOnClickListener {
Toast.makeText(this, tvMsg.text.toString().trim(), Toast.LENGTH_LONG).show()
}
但是,如果你使用了Kotlin的Android扩展插件,无需使用findViewById()获取控件,可以直接通过布局文件中的id进行访问
import kotlinx.android.synthetic.main.activity_main.* // 引入布局文件
// tvMsg是对Activity的一项扩展属性,与activity_main.xml中声明的id为tvMsg的控件具有一样的类型,所以是TextView
tvMsg.text = "This is a TextView"
tvMsg.setOnClickListener {
Toast.makeText(this, tvMsg.text.toString().trim(), Toast.LENGTH_LONG).show()
}
以上的示例,是Kotlin的Android扩展插件中的视图绑定,看着是不是很方便简洁呢?其实Kotlin的Android扩展还有很多其他用途。
使用Kotlin Android扩展
配置扩展
Kotlin Android扩展,必须是在Gradle环境下才能使用
配置扩展,仅需要在模块的 build.gradle 文件中启用 Gradle 安卓扩展插件即可:
apply plugin: 'kotlin-android-extensions'
导入合成属性
在需要用一行代码便可导入指定布局文件中的所有属性
import kotlinx.android.synthetic.<channel_name>.<layout_xml_file_name>.*
以上可变参数中:
channel_name是指渠道名称,如果你的项目支持多个渠道(productFlavors),这里写对应的渠道名称,如果没有,默认为mainlayout_xml_file_name是布局文件名称
导入完成后即可调用在xml文件中以视图控件命名属性的对应扩展,如下:
<TextView
android:id="@+id/tvMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
你将获得一个名为tvMsg的属性
tvMsg.text = "This is a TextView"
更多推荐



所有评论(0)