kotlin之不需要findViewById
我们经常写android代码中,经常要查找id,比如10个button需要调用10次
findViewById
这个问题在kotlin中就不复存在了,使用Kotlin编写的Android项目在app/build.gradle
文件引用如下:
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
buildFeatures {
prefab true
}
}
这个插件会根据布局中文件中定义的控件id自动生成一个具有相同名称的变量,可以在Activity直接使用这个变量,而不再调用findViewById()
比如布局中有个button1
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"
/>
</LinearLayout>
然后通过binding就可以调用button1了
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.brooks.activitytest.databinding.FirstLayoutBinding
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.title.view.*
class FirstActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = FirstLayoutBinding.inflate(layoutInflater) // 通过binding就可以调用其他button了
setContentView(binding.root)
//binding.button1.setOnClickListener {
// Toast.makeText(this, "You clicked Button 1", Toast.LENGTH_SHORT).show()
//}
button1.setOnClickListener {
Toast.makeText(this, "You clicked Button 1", Toast.LENGTH_SHORT).show()
}
}
}
import kotlinx.android.synthetic.main.activity_main.*
和import kotlinx.android.synthetic.main.title.view.*
就可以直接通过id控制控件啦!!!