Kotlin-24-findViewById 拜拜

目录

1、kotlin-android-extensions

2、依赖kotlin-android-extensions

3、布局代码

4、Activity代码

5、实现原理


1、kotlin-android-extensions

kotlin-android-extensions是kotlin为Android专门提供的扩展插件,它就是实现替代findViewById的强大工具。

2、依赖kotlin-android-extensions

当我们用AndroidStudio创建一个Kotlin项目的时候,会自动给我们依赖这个插件,当然我们也能自己依赖。

3、布局代码

这是一个创建项目的初始化布局,我改了TextView的id-----main_text。

<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"
    tools:context=".test1.MainActivity">

    <TextView
        android:id="@+id/main_text"
        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>

4、Activity代码

可以明显的看到initView()方法中,我们可以直接使用xml中TextView的Id   main_text 来做一些UI操作。initView1()是为了做对比写出来的。

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

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        initView1()
    }
    private fun initView() {
        main_text.text = "我"
        main_text.textSize = 30f
    }
    private fun initView1() {
        val text = findViewById<TextView>(R.id.main_text)
        text.setTextColor(resources.getColor(R.color.colorAccent))
    }
}

5、实现原理

我们先来看一下它编译后的代码。

绿色框:缓存View和其id 的集合。

黄色框:findViewById的方法所在,每次取view都先判断集合中有没有

红色框:当我们调用 main_text.text = "我" 会通过黄色框中的方法获取指定的view

蓝色框:Activity onDestroy的时候,清空对view的缓存

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值