Kotlin View Binding,findViewById() 终结者

2023-05-16

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 内容持续更新中~

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Kotlin View Binding,findViewById() 终结者 的相关文章

随机推荐