Kotlin View Binding,findViewById() 终结者

时间:2022-06-19
本文章向大家介绍Kotlin View Binding,findViewById() 终结者,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

AS 中如何配置 View Binding

仅需 2 步,简单快速:

1. 配置依赖

安卓扩展是 IntelliJ IDEA 与 Android Studio 的 Kotlin 插件的组成之一,因此不需要再单独安装额外插件。

开发者仅需要在 项目根目录 → app → build.gradle 文件中启用 Gradle 安卓扩展插件即可:

apply plugin:'kotlin-android-extensions'
2. 导入合成属性

Activity内仅需要一行即可非常方便导入指定布局文件中所有控件属性:

import kotlinx.android.synthetic.main.<布局>.*

假设当前布局文件是 activity_main.xml,我们只需要引入

kotlinx.android.synthetic.main.activity_main.*。

若需要调用 View 的合成属性,同时还应该导入

kotlinx.android.synthetic.main.activity_main.view.*。

导入完成后即可调用在xml文件中以视图控件命名属性的对应扩展!


使用实例

1. lauout文件中布局TextView组件
<TextView

    android:id="@+id/hello"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"/>
2. Activity中调用对象并重新赋值
hello.text = "Hello World!"
3. 运行结果

国际惯例

贴上完整源码

完整 Layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#333333"/>

</LinearLayout>
完整 Activity.kt
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_find_view_binding.*

/**
 * @des Kotlin View Binding 实例类
 * @author liyongli 20190301
 * */
class FindViewBindingActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_find_view_binding)

        // 可通过 TextView 的 id 直接赋值
        hello.text = "Hello World!"

    }
}

本篇到此完结,更多 Kotlin For Android Development 内容持续更新中~

期待您点击关注或点击头像浏览更多移动端开发技术干货