目录
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的缓存